diff --git a/CLAUDE.md b/CLAUDE.md index e81254f..218e9e9 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -15,3 +15,7 @@ npm run build ``` The steps are defined in `.github/workflows/ci.yml`. A failure blocks the deploy job and emails the owner. It happened once after running only tsc and vitest: eslint (`react-hooks/purity`, `performance.now` in a component) and prettier (a SCSS file) both failed in CI. + +## While iterating + +When making changes with the owner in a back-and-forth session, don't run the test suite (or the rest of the CI steps) after each change, unless they ask for it. The tests take long enough to slow the iteration down significantly. Update the tests alongside the code as usual, so that they are right when they do get run, and say that they haven't been run. The full CI run before a push (above) still applies. diff --git a/web/index.html b/web/index.html index b0f1115..c4718ba 100644 --- a/web/index.html +++ b/web/index.html @@ -1,7 +1,7 @@ - + diff --git a/web/public/favicon.svg b/web/public/favicon.svg new file mode 100644 index 0000000..11e4c5f --- /dev/null +++ b/web/public/favicon.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/web/src/App.test.tsx b/web/src/App.test.tsx index 8d0b50d..01b9eec 100644 --- a/web/src/App.test.tsx +++ b/web/src/App.test.tsx @@ -1,10 +1,9 @@ -import { act, cleanup, fireEvent, render, screen } from "@testing-library/react"; +import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { MemoryRouter } from "react-router-dom"; import App from "@/App"; import { defaultColors } from "@/config"; import { createDemoGame } from "@/demoGame"; -import { DEFAULT_GAME_NAME } from "@/Game"; import { lastRound, partialScores, totalScore, totalScoreRange } from "@/utils/Scores"; type User = ReturnType; @@ -32,14 +31,14 @@ async function addSecondPlayer(user: User, container: HTMLElement) { describe("demo game", () => { it("is only loaded when the URL asks for it", () => { renderApp("/"); - expect(screen.queryByText("Friday Night Rummy")).toBeNull(); + expect(screen.queryByRole("button", { name: /Continue Game/ })).toBeNull(); }); it("loads with ?demo, and plays from its latest round", async () => { const user = userEvent.setup(); const { container } = renderApp("/?demo"); - expect(screen.getByText("Friday Night Rummy")).toBeTruthy(); + expect(screen.getByRole("button", { name: /Continue Game/ })).toBeTruthy(); await user.click(screen.getByText("Continue Game")); const demo = createDemoGame(); @@ -112,7 +111,7 @@ describe("demo game", () => { }); describe("title page", () => { - it("starts a new game with one player, in edit mode", async () => { + it("starts a new game with one player, with the window for editing the players open", async () => { const user = userEvent.setup(); const { container } = renderApp("/"); @@ -121,31 +120,7 @@ describe("title page", () => { expect(container.querySelectorAll(".player")).toHaveLength(1); expect(container.querySelector(".player-name-input")!.value).toBe("Player 1"); expect(screen.getByText("Edit Players")).toBeTruthy(); - expect(container.querySelector(".player.editing")).not.toBeNull(); - }); - - it("starts a new game with the game name selected", async () => { - const user = userEvent.setup(); - const { container } = renderApp("/"); - - await user.click(screen.getByText("Start New Game")); - - const input = container.querySelector(".game-name-input")!; - expect(document.activeElement).toBe(input); - expect([input.selectionStart, input.selectionEnd]).toEqual([0, input.value.length]); - - // Typing replaces the whole name - await user.keyboard("Rummy"); - expect(input.value).toBe("Rummy"); - }); - - it("does not select the game name when entering edit mode later", async () => { - const user = userEvent.setup(); - const { container } = renderApp(); - - await user.click(container.querySelector(".done-button, .edit-players-button")!); - - expect(document.activeElement).not.toBe(container.querySelector(".game-name-input")); + expect(container.querySelector(".edit-players-dialog")).not.toBeNull(); }); it("starts a new game even after playing one", async () => { @@ -176,7 +151,6 @@ describe("title page", () => { expect(screen.getByRole("button", { name: "Start New Game" }).classList).toContain("primary"); const continueButton = screen.getByRole("button", { name: /Continue Game/ }); expect(continueButton.classList).not.toContain("primary"); - expect(continueButton.textContent).toContain("Friday Night Rummy"); expect(continueButton.textContent).toContain(`${createDemoGame().scorecards.length} players`); expect(demo.container.querySelectorAll(".score-lines-backdrop polyline")).toHaveLength(5); }); @@ -190,15 +164,14 @@ describe("title page", () => { await user.click(screen.getByText("Continue Game")); expect(container.querySelector(".game-play-background")).not.toBeNull(); - expect(container.querySelector(".player.editing")).toBeNull(); + expect(container.querySelector(".edit-players-dialog")).toBeNull(); expect(screen.queryByText("Edit Players")).toBeNull(); }); }); describe("game play page", () => { - it("renders the player and the game name", () => { + it("renders the player", () => { renderApp(); - expect(screen.getByText("New Game (click to edit)")).toBeTruthy(); expect(screen.getByText("Player 1")).toBeTruthy(); }); @@ -213,7 +186,7 @@ describe("game play page", () => { const user = userEvent.setup(); const { container } = renderApp(); - await user.click(container.querySelector(".done-button, .edit-players-button")!); + await user.click(container.querySelector(".edit-players-button")!); await user.click(container.querySelector(".add-player-button")!); const input = document.activeElement as HTMLInputElement; @@ -221,49 +194,28 @@ describe("game play page", () => { expect(input.value).toBe("Player 2"); }); - it("shows player names as plain text normally and as text boxes in edit mode", async () => { + it("shows player names as plain text in the list, and as text boxes in the window for editing them", async () => { const user = userEvent.setup(); const { container } = renderApp(); expect(container.querySelector(".player-name-input")).toBeNull(); - await user.click(container.querySelector(".done-button, .edit-players-button")!); + await user.click(container.querySelector(".edit-players-button")!); expect(container.querySelector(".player-name-input")!.value).toBe("Player 1"); - // The game name is not part of edit mode - expect(container.querySelector(".game-name-input")).toBeNull(); - await user.click(container.querySelector(".done-button, .edit-players-button")!); + await user.click(container.querySelector(".done-button")!); expect(container.querySelector(".player-name-input")).toBeNull(); }); - it("renames the game by pressing its name, whether or not players are being edited", async () => { - const user = userEvent.setup(); - const { container } = renderApp(); - - await user.click(container.querySelector(".game-name-label")!); - const input = container.querySelector(".game-name-input")!; - expect(input.value).toBe("New Game (click to edit)"); - expect(container.querySelector(".player-name-input")).toBeNull(); // Not editing the players - - await user.clear(input); - await user.type(input, "Rummy{Enter}"); - expect(container.querySelector(".game-name-input")).toBeNull(); - expect(screen.getByText("Rummy")).toBeTruthy(); - }); - - it("renames the game and players from their text boxes", async () => { + it("renames players from their text boxes", async () => { const user = userEvent.setup(); const { container } = renderApp(); - await user.click(container.querySelector(".game-name-label")!); - await user.clear(container.querySelector(".game-name-input")!); - await user.type(container.querySelector(".game-name-input")!, "Rummy{Enter}"); await user.click(container.querySelector(".edit-players-button")!); await user.clear(container.querySelector(".player-name-input")!); await user.type(container.querySelector(".player-name-input")!, "Ada{Enter}"); await user.click(container.querySelector(".done-button")!); - expect(screen.getByText("Rummy")).toBeTruthy(); expect(screen.getByText("Ada")).toBeTruthy(); }); @@ -394,6 +346,47 @@ describe("game play page", () => { expect(container.querySelector(".score-value")!.textContent).toBe("55"); }); + it("shows a key of the keypad as pressed while its key on the keyboard is held down", () => { + vi.useFakeTimers(); + try { + const { container } = renderApp(); + const pressed = () => + Array.from(container.querySelectorAll(".key.pressed")).map((el) => el.className); + + fireEvent.keyDown(window, { key: "5" }); + expect(key(container, "5").classList.contains("pressed")).toBe(true); + fireEvent.keyUp(window, { key: "5" }); // A quick tap: it stays pressed a moment longer + expect(key(container, "5").classList.contains("pressed")).toBe(true); + act(() => vi.advanceTimersByTime(200)); + expect(pressed()).toEqual([]); + + for (const [pressedKey, keypadClass] of [ + ["-", "key-negate"], + ["Backspace", "key-backspace"], + ["Enter", "key-enter"], + [".", "key-point"], + ] as const) { + fireEvent.keyDown(window, { key: pressedKey }); + expect(container.querySelector(`.${keypadClass}`)!.classList.contains("pressed")).toBe( + true, + ); + fireEvent.keyUp(window, { key: pressedKey }); + act(() => vi.advanceTimersByTime(200)); + } + } finally { + vi.useRealTimers(); + } + }); + + it("does not show a key as pressed for a key of the keyboard that has no key on the keypad", () => { + const { container } = renderApp(); + + fireEvent.keyDown(window, { key: "ArrowDown" }); + fireEvent.keyDown(window, { key: "x" }); + + expect(container.querySelectorAll(".key.pressed")).toHaveLength(0); + }); + it("only ever shows one key as pressed", () => { const { container } = renderApp(); @@ -430,13 +423,12 @@ describe("game play page", () => { const user = userEvent.setup(); const { container } = renderApp(); await user.click(container.querySelector(".edit-players-button")!); - const list = container.querySelector(".player-list")!; - const footer = container.querySelector(".list-footer")!; + const list = container.querySelector(".edit-players-list")!; + const footer = container.querySelector(".edit-players-footer")!; expect(footer.querySelector(".add-player-button")).not.toBeNull(); expect(list.contains(footer)).toBe(false); expect(footer.parentElement).toBe(list.parentElement); - expect(container.querySelector(".round-buttons")!.parentElement).toBe(list.parentElement); }); it("scrolls the next player into view when the keypad moves on to them", async () => { @@ -450,7 +442,9 @@ describe("game play page", () => { const rows = container.querySelectorAll(".player"); const lastCall = scrollIntoView.mock.contexts.length - 1; expect(scrollIntoView.mock.contexts[lastCall]).toBe(rows[1]); - expect(scrollIntoView.mock.calls[lastCall]).toEqual([{ block: "nearest" }]); + expect(scrollIntoView.mock.calls[lastCall]).toEqual([ + { block: "center", behavior: "smooth" }, + ]); }); it("scrolls to the player entered on, after a score moves the selection along", async () => { @@ -469,7 +463,7 @@ describe("game play page", () => { it("doesn't scroll around in edit mode", async () => { const user = userEvent.setup(); const { container } = renderApp(); - await user.click(container.querySelector(".done-button, .edit-players-button")!); + await user.click(container.querySelector(".edit-players-button")!); const scrollIntoView = spyOnScrollIntoView(); fireEvent.keyDown(window, { key: "ArrowDown" }); @@ -507,9 +501,9 @@ describe("game play page", () => { function openLongList() { const view = renderApp("/?demo"); fireEvent.click(screen.getByText("Continue Game")); - fireEvent.click(view.container.querySelector(".done-button, .edit-players-button")!); + fireEvent.click(view.container.querySelector(".edit-players-button")!); - const list = view.container.querySelector(".player-list")!; + const list = view.container.querySelector(".edit-players-list")!; list.getBoundingClientRect = () => rect(listTop, listBottom - listTop); // jsdom doesn't scroll, so keep track of how far the list has been scrolled Object.defineProperty(list, "scrollTop", { @@ -519,7 +513,7 @@ describe("game play page", () => { list.dispatchEvent(new Event("scroll")); }, }); - const rows = () => Array.from(view.container.querySelectorAll(".player")); + const rows = () => Array.from(view.container.querySelectorAll(".edit-player")); for (const row of rows()) { row.getBoundingClientRect = () => rect(rows().indexOf(row) * rowHeight, rowHeight - 4); } @@ -661,8 +655,8 @@ describe("game play page", () => { async function openPickerWithSwatchAt(y: number) { const user = userEvent.setup(); const view = renderApp(); - await user.click(view.container.querySelector(".done-button, .edit-players-button")!); - const swatch = view.container.querySelector(".player-color")!; + await user.click(view.container.querySelector(".edit-players-button")!); + const swatch = view.container.querySelector(".edit-player .player-color")!; swatch.getBoundingClientRect = () => ({ x: 40, @@ -682,7 +676,7 @@ describe("game play page", () => { Object.defineProperty(window, "innerHeight", { value: 800, configurable: true }); }); - it("stays in edit mode while choosing a color and when closing the picker", async () => { + it("keeps the window open while choosing a color and when closing the picker", async () => { const user = userEvent.setup(); const picker = await openPickerWithSwatchAt(300); await user.click(picker.querySelector(".color-card")!); @@ -691,14 +685,25 @@ describe("game play page", () => { expect(document.querySelector(".done-button")).not.toBeNull(); }); + it("can be closed with its own Done button, which the phone layout shows", async () => { + const user = userEvent.setup(); + await openPickerWithSwatchAt(300); + const background = document.querySelector(".color-select-background")!; + + await user.click(screen.getByRole("button", { name: "Close color picker" })); + // It fades out first, and is taken away once that is over, which jsdom has no way to say + expect(background.classList).toContain("closing"); + expect(document.querySelector(".edit-players-dialog")).not.toBeNull(); // Only the picker + }); + it("sits next to the color it is for", async () => { const picker = await openPickerWithSwatchAt(300); - expect(picker.style.top).toBe("265px"); + expect(picker.style.top).toBe("185px"); // The middle of the 40 high color, 320, less half of 270 }); it("stays on the screen when the color is near the bottom", async () => { const picker = await openPickerWithSwatchAt(780); - expect(picker.style.top).toBe("686px"); // 800 high, minus the picker's 102 and a 12 margin + expect(picker.style.top).toBe("518px"); // 800 high, minus the picker's 270 and a 12 margin }); it("stays on the screen when the color is near the top", async () => { @@ -712,7 +717,7 @@ describe("game play page", () => { const user = userEvent.setup(); const { container } = renderApp(); - await user.click(container.querySelector(".done-button, .edit-players-button")!); + await user.click(container.querySelector(".edit-players-button")!); await user.click(container.querySelector(".player-name-input")!); await user.keyboard("7{Enter}"); @@ -862,16 +867,16 @@ describe("game play page", () => { it("says how", async () => { await playTwoRounds(); - expect(screen.getByText("Tap a score to edit it")).toBeTruthy(); + expect(screen.getByText("Click a score to edit it")).toBeTruthy(); }); }); it("says so when there are no players", async () => { const user = userEvent.setup(); const { container } = renderApp(); - await user.click(container.querySelector(".done-button, .edit-players-button")!); + await user.click(container.querySelector(".edit-players-button")!); await user.click(container.querySelector(".delete-button")!); - await user.click(container.querySelector(".done-button, .edit-players-button")!); + await user.click(container.querySelector(".done-button")!); await user.click(container.querySelectorAll(".buttons-section button")[2]!); // The player list says something of its own, so look at the table's @@ -1147,11 +1152,11 @@ describe("game play page", () => { const user = userEvent.setup(); const { container } = renderApp(); - await user.click(container.querySelector(".done-button, .edit-players-button")!); + await user.click(container.querySelector(".edit-players-button")!); for (const button of Array.from(container.querySelectorAll(".delete-button"))) { await user.click(button); } - await user.click(container.querySelector(".done-button, .edit-players-button")!); + await user.click(container.querySelector(".done-button")!); await user.click(container.querySelectorAll(".buttons-section button")[1]!); expect(container.querySelector(".plot-scores-content")).not.toBeNull(); @@ -1182,17 +1187,12 @@ describe("saving the game", () => { it("brings the game back after a reload, and Continue Game picks it up", async () => { const user = userEvent.setup(); const first = renderApp("/play/"); - await user.click(first.container.querySelector(".game-name-label")!); - await user.clear(first.container.querySelector(".game-name-input")!); - await user.type(first.container.querySelector(".game-name-input")!, "Rummy"); - await user.keyboard("{Enter}"); fireEvent.keyDown(window, { key: "9" }); fireEvent.keyDown(window, { key: "Enter" }); first.unmount(); // Closing the page const second = renderApp("/"); expect(continueButton().hasAttribute("disabled")).toBe(false); - expect(screen.getByText("Rummy")).toBeTruthy(); await user.click(screen.getByText("Continue Game")); expect(shownScores(second.container)).toEqual(["9"]); }); @@ -1207,7 +1207,6 @@ describe("saving the game", () => { const second = renderApp("/"); await user.click(screen.getByText("Start New Game")); - expect(savedGame().game.name).toBe(DEFAULT_GAME_NAME); expect(savedGame().game.scorecards[0].scores).toEqual([0]); expect(second.container.querySelectorAll(".player")).toHaveLength(1); }); @@ -1234,14 +1233,15 @@ describe("saving the game", () => { const before = localStorage.getItem("scoreplot.game"); const { container } = renderApp("/?demo"); - expect(screen.getByText("Friday Night Rummy")).toBeTruthy(); - expect(screen.queryByText("My Real Game")).toBeNull(); + expect(screen.getByRole("button", { name: /Continue Game/ }).textContent).toContain( + `${createDemoGame().scorecards.length} players`, + ); // Play: the "?demo" has gone from the address by now, but it is still the demo game await user.click(screen.getByText("Continue Game")); fireEvent.keyDown(window, { key: "4" }); fireEvent.keyDown(window, { key: "Enter" }); - await user.click(container.querySelector(".done-button, .edit-players-button")!); + await user.click(container.querySelector(".edit-players-button")!); await user.click(container.querySelector(".add-player-button")!); expect(localStorage.getItem("scoreplot.game")).toBe(before); @@ -1275,15 +1275,15 @@ describe("undoing", () => { async function threePlayers() { const user = userEvent.setup(); const view = renderApp("/play/"); - await user.click(view.container.querySelector(".done-button, .edit-players-button")!); + await user.click(view.container.querySelector(".edit-players-button")!); await user.click(view.container.querySelector(".add-player-button")!); await user.click(view.container.querySelector(".add-player-button")!); - await user.click(view.container.querySelector(".done-button, .edit-players-button")!); + await user.click(view.container.querySelector(".done-button")!); for (const score of ["4", "5", "6"]) { fireEvent.keyDown(window, { key: score }); fireEvent.keyDown(window, { key: "Enter" }); } - await user.click(view.container.querySelector(".done-button, .edit-players-button")!); + await user.click(view.container.querySelector(".edit-players-button")!); return { user, ...view }; } @@ -1309,7 +1309,7 @@ describe("undoing", () => { expect( container.querySelectorAll(".player-color")[1]!.style.backgroundColor, ).toBe(colorBefore); - await user.click(container.querySelector(".done-button, .edit-players-button")!); + await user.click(container.querySelector(".edit-players-button")!); expect(shownScores(container)).toEqual(["4", "5", "6"]); expect(toastMessages()).toEqual([]); }); @@ -1343,88 +1343,328 @@ describe("undoing", () => { }); describe("starting a new game", () => { - /** The title page, after playing a game called Rummy in which Player 1 scored 8 */ - async function afterPlayingRummy() { + it("does not offer to undo it, even over a game that was played", async () => { const user = userEvent.setup(); const first = renderApp("/play/"); - await user.click(first.container.querySelector(".game-name-label")!); - await user.clear(first.container.querySelector(".game-name-input")!); - await user.type(first.container.querySelector(".game-name-input")!, "Rummy"); - await user.keyboard("{Enter}"); fireEvent.keyDown(window, { key: "8" }); fireEvent.keyDown(window, { key: "Enter" }); first.unmount(); - return { user, ...renderApp("/") }; - } - - it("says so, with a way to undo it, over the game that was started", async () => { - const { user, container } = await afterPlayingRummy(); + const { container } = renderApp("/"); await user.click(screen.getByText("Start New Game")); - expect(toastMessages()).toEqual(["Started a new game"]); + expect(toastMessages()).toEqual([]); expect(container.querySelector(".game-play-background")).not.toBeNull(); - expect(container.querySelectorAll(".player")).toHaveLength(1); expect(shownScores(container)).toEqual(["0"]); }); - it("brings back the game that was there before", async () => { - const { user, container } = await afterPlayingRummy(); - const savedName = () => JSON.parse(localStorage.getItem("scoreplot.game")!).game.name; + it("selects the first player's name in the window that opens, ready to be typed over", async () => { + const user = userEvent.setup(); + renderApp("/"); await user.click(screen.getByText("Start New Game")); - expect(savedName()).toBe(DEFAULT_GAME_NAME); - await user.click(screen.getByRole("button", { name: "Undo" })); - expect(savedName()).toBe("Rummy"); - await user.click(container.querySelector(".done-button, .edit-players-button")!); // Out of edit mode, as new games start in it - expect(shownScores(container)).toEqual(["8"]); - expect(container.querySelector(".game-name-label")!.textContent).toBe("Rummy"); + const input = document.querySelector(".player-name-input")!; + expect(document.activeElement).toBe(input); + expect([input.selectionStart, input.selectionEnd]).toEqual([0, input.value.length]); + await user.keyboard("Ada"); + expect(input.value).toBe("Ada"); }); - it("does not bother when there was nothing to lose", async () => { + it("selects a name that is pressed, ready to be typed over", async () => { const user = userEvent.setup(); - renderApp("/"); - await user.click(screen.getByText("Start New Game")); - expect(toastMessages()).toEqual([]); + const { container } = renderApp("/play/"); + await user.click(container.querySelector(".edit-players-button")!); + const input = container.querySelector(".player-name-input")!; + + await user.click(input); + + expect(document.activeElement).toBe(input); + expect([input.selectionStart, input.selectionEnd]).toEqual([0, input.value.length]); }); - it("does not bother when the game had not been touched", async () => { + it("does not select a name that is tapped, as that brings up the phone's menu for a selection", async () => { + const user = userEvent.setup(); + const { container } = renderApp("/play/"); + await user.click(container.querySelector(".edit-players-button")!); + const input = container.querySelector(".player-name-input")!; + + await user.pointer({ keys: "[TouchA]", target: input }); + + expect(document.activeElement).toBe(input); + expect(input.selectionStart).toBe(input.selectionEnd); + }); + + it("does not select a name that is tapped while another name has the focus", async () => { + const user = userEvent.setup(); + const { container } = renderApp("/play/"); + await user.click(container.querySelector(".edit-players-button")!); + await user.click(container.querySelector(".add-player-button")!); // The new name has the focus + const [first, second] = Array.from( + container.querySelectorAll(".player-name-input"), + ); + + await user.pointer({ keys: "[TouchA]", target: first! }); + expect(document.activeElement).toBe(first); + expect(first!.selectionStart).toBe(first!.selectionEnd); + + await user.pointer({ keys: "[TouchA]", target: second! }); + expect(document.activeElement).toBe(second); + expect(second!.selectionStart).toBe(second!.selectionEnd); + }); + + it("selects a name for the new game only, and not when the window is opened again", async () => { const user = userEvent.setup(); const { container } = renderApp("/"); - await user.click(screen.getByText("Start New Game")); // A game, but a blank one - await user.click(container.querySelector(".button-home")!); await user.click(screen.getByText("Start New Game")); - expect(toastMessages()).toEqual([]); + expect(document.activeElement).toBe(container.querySelector(".player-name-input")); + + await user.click(container.querySelector(".done-button")!); + await user.click(container.querySelector(".edit-players-button")!); + + expect(document.activeElement).toBe(container.querySelector(".edit-players-dialog")); + }); + + it("does not select a name when the window is opened with the button", async () => { + const user = userEvent.setup(); + const { container } = renderApp("/play/"); + + await user.click(container.querySelector(".edit-players-button")!); + + expect(document.activeElement).toBe(container.querySelector(".edit-players-dialog")); }); }); }); describe("pressing a toast while editing", () => { - it("does not leave edit mode, so that you can go on editing after an Undo", async () => { + it("does not close the window for editing, so that you can go on editing after an Undo", async () => { const user = userEvent.setup(); const { container } = renderApp("/play/"); - await user.click(container.querySelector(".done-button, .edit-players-button")!); + await user.click(container.querySelector(".edit-players-button")!); await user.click(container.querySelector(".add-player-button")!); await user.click(container.querySelectorAll(".delete-button")[1]!); expect(container.querySelector(".toast")).not.toBeNull(); await user.click(screen.getByRole("button", { name: "Undo" })); - expect(container.querySelectorAll(".player.editing")).toHaveLength(2); + expect(container.querySelectorAll(".edit-player")).toHaveLength(2); expect(container.querySelector(".add-player-button")).not.toBeNull(); }); - it("still leaves edit mode for a press anywhere else", async () => { + it("does not close the window for a press on the page behind it", async () => { const user = userEvent.setup(); const { container } = renderApp("/play/"); - await user.click(container.querySelector(".done-button, .edit-players-button")!); + await user.click(container.querySelector(".edit-players-button")!); await user.click(container.querySelector(".add-player-button")!); await user.click(container.querySelectorAll(".delete-button")[1]!); - await user.click(container.querySelector(".content-section")!); + await user.click(container.querySelector(".edit-players-backdrop")!); + + expect(container.querySelector(".edit-players-dialog")).not.toBeNull(); + }); +}); + +describe("closing the window for editing players", () => { + it("closes with Escape", async () => { + const user = userEvent.setup(); + const { container } = renderApp("/play/"); + await user.click(container.querySelector(".edit-players-button")!); + + await user.keyboard("{Escape}"); + + expect(container.querySelector(".edit-players-dialog")).toBeNull(); + }); + + it("closes with Done", async () => { + const user = userEvent.setup(); + const { container } = renderApp("/play/"); + await user.click(container.querySelector(".edit-players-button")!); - expect(container.querySelector(".player.editing")).toBeNull(); + await user.click(container.querySelector(".done-button")!); + + expect(container.querySelector(".edit-players-dialog")).toBeNull(); + }); +}); + +describe("the window for editing players on a touch screen", () => { + const originalMatchMedia = window.matchMedia; + beforeEach(() => { + window.matchMedia = ((query: string) => ({ + matches: query.includes("pointer: coarse"), + media: query, + addEventListener: () => {}, + removeEventListener: () => {}, + })) as unknown as typeof window.matchMedia; + }); + afterEach(() => { + window.matchMedia = originalMatchMedia; + }); + + const nameBoxes = (container: HTMLElement) => + Array.from(container.querySelectorAll(".player-name-input")); + + it("puts the cursor in a name as it opens, so that the keyboard is up", async () => { + const user = userEvent.setup(); + const { container } = renderApp("/play/"); + + await user.click(container.querySelector(".edit-players-button")!); + + const [box] = nameBoxes(container); + expect(document.activeElement).toBe(box); + expect(box!.selectionStart).toBe(box!.selectionEnd); // Opened by a tap, so nothing is selected + }); + + it("keeps the cursor in the name when something else in the window is pressed", async () => { + const user = userEvent.setup(); + const { container } = renderApp("/play/"); + await user.click(container.querySelector(".edit-players-button")!); + + const title = container.querySelector(".edit-players-title")!; + const notCancelled = fireEvent.mouseDown(title); // False when the press is stopped taking the focus + + expect(notCancelled).toBe(false); + expect(document.activeElement).toBe(nameBoxes(container)[0]); + }); + + it("keeps the cursor in the name when the page behind the window is pressed", async () => { + const user = userEvent.setup(); + const { container } = renderApp("/play/"); + await user.click(container.querySelector(".edit-players-button")!); + + const notCancelled = fireEvent.mouseDown(container.querySelector(".edit-players-backdrop")!); + + expect(notCancelled).toBe(false); + expect(document.activeElement).toBe(nameBoxes(container)[0]); + }); + + it("goes on to the next name with Enter, rather than putting the keyboard away", async () => { + const user = userEvent.setup(); + const { container } = renderApp("/play/"); + await user.click(container.querySelector(".edit-players-button")!); + await user.click(container.querySelector(".add-player-button")!); + const [first, second] = nameBoxes(container); + first!.focus(); + + await user.keyboard("{Enter}"); + + expect(document.activeElement).toBe(second); + }); + + it("puts the cursor back in a name after the one that had it is deleted", async () => { + const user = userEvent.setup(); + const { container } = renderApp("/play/"); + await user.click(container.querySelector(".edit-players-button")!); + await user.click(container.querySelector(".add-player-button")!); // The new name has the focus + + await user.click(container.querySelectorAll(".delete-button")[1]!); + + await waitFor(() => expect(document.activeElement).toBe(nameBoxes(container)[0])); + }); +}); + +describe("the tabs on a screen that is taller than it is wide", () => { + const originalMatchMedia = window.matchMedia; + beforeEach(() => { + window.matchMedia = ((query: string) => ({ + matches: query.includes("max-aspect-ratio"), + media: query, + addEventListener: () => {}, + removeEventListener: () => {}, + })) as unknown as typeof window.matchMedia; + }); + afterEach(() => { + window.matchMedia = originalMatchMedia; + }); + + it("has no button for expanding the player list", () => { + renderApp("/play/"); + expect(screen.queryByRole("button", { name: /player list/i })).toBeNull(); + }); + + it("expands the list, and drops the tab, when the tab that is showing is pressed", async () => { + const user = userEvent.setup(); + const { container } = renderApp("/play/"); + const keypad = screen.getByRole("tab", { name: "Keypad" }); + expect(keypad.getAttribute("aria-selected")).toBe("true"); + + await user.click(keypad); + + expect(container.querySelector(".list-expanded")).not.toBeNull(); + expect(keypad.getAttribute("aria-selected")).toBe("false"); + expect( + screen.getAllByRole("tab").every((tab) => tab.getAttribute("aria-selected") === "false"), + ).toBe(true); + }); + + it("shows the total scores in the list on its own, as it does after the plot or the table", async () => { + const user = userEvent.setup(); + const { container } = renderApp("/play/"); + const heading = () => container.querySelector(".round-label")!.textContent; + expect(heading()).toMatch(/^Round /); + + await user.click(screen.getByRole("tab", { name: "Keypad" })); // Pressed while showing: none selected + + expect(heading()).toBe("Total Scores"); + + await user.click(screen.getByRole("tab", { name: "Keypad" })); + + expect(heading()).toMatch(/^Round /); + }); + + it("does not take scores from the keyboard while the list is on its own", async () => { + const user = userEvent.setup(); + const { container } = renderApp("/play/"); + await user.click(screen.getByRole("tab", { name: "Keypad" })); + + fireEvent.keyDown(window, { key: "7" }); + + expect(container.querySelector(".score-value")!.textContent).toBe("0"); + }); + + it("brings the tab back, and shrinks the list, when a tab is pressed after that", async () => { + const user = userEvent.setup(); + const { container } = renderApp("/play/"); + await user.click(screen.getByRole("tab", { name: "Keypad" })); + + await user.click(screen.getByRole("tab", { name: "Plot" })); + + expect(container.querySelector(".list-expanded")).toBeNull(); + expect(screen.getByRole("tab", { name: "Plot" }).getAttribute("aria-selected")).toBe("true"); + }); + + it("does the same for the plot and the table", async () => { + const user = userEvent.setup(); + const { container } = renderApp("/play/"); + for (const name of ["Plot", "Table"]) { + await user.click(screen.getByRole("tab", { name })); + expect(container.querySelector(".list-expanded")).toBeNull(); + await user.click(screen.getByRole("tab", { name })); + expect(container.querySelector(".list-expanded")).not.toBeNull(); + } + }); + + it("gives the table the room that the player list would have had", async () => { + const user = userEvent.setup(); + const { container } = renderApp("/play/"); + expect(container.querySelector(".table-showing")).toBeNull(); + + await user.click(screen.getByRole("tab", { name: "Table" })); + expect(container.querySelector(".table-showing")).not.toBeNull(); + + await user.click(screen.getByRole("tab", { name: "Plot" })); + expect(container.querySelector(".table-showing")).toBeNull(); + }); +}); + +describe("pressing the tab that is showing on a wide screen", () => { + it("does nothing, as the list is beside the panel already", async () => { + const user = userEvent.setup(); + const { container } = renderApp("/play/"); + + await user.click(screen.getByRole("tab", { name: "Keypad" })); + + expect(container.querySelector(".list-expanded")).toBeNull(); + expect(screen.getByRole("tab", { name: "Keypad" }).getAttribute("aria-selected")).toBe("true"); }); }); @@ -1473,10 +1713,10 @@ describe("keypad caption", () => { it("follows a player being renamed", async () => { const user = userEvent.setup(); const { container } = renderApp("/play/"); - await user.click(container.querySelector(".done-button, .edit-players-button")!); + await user.click(container.querySelector(".edit-players-button")!); await user.clear(container.querySelector(".player-name-input")!); await user.type(container.querySelector(".player-name-input")!, "Ada"); - await user.click(container.querySelector(".done-button, .edit-players-button")!); + await user.click(container.querySelector(".done-button")!); expect(caption(container)).toBe("Ada · Round 1"); }); @@ -1484,37 +1724,39 @@ describe("keypad caption", () => { it("copes with a player whose name has been cleared", async () => { const user = userEvent.setup(); const { container } = renderApp("/play/"); - await user.click(container.querySelector(".done-button, .edit-players-button")!); + await user.click(container.querySelector(".edit-players-button")!); await user.clear(container.querySelector(".player-name-input")!); - await user.click(container.querySelector(".done-button, .edit-players-button")!); + await user.click(container.querySelector(".done-button")!); expect(caption(container)).toBe("Player · Round 1"); }); - it("says what to do when the player list is empty, in and out of edit mode", async () => { + it("says what to do when there are no players, in the list and in the window for editing them", async () => { const user = userEvent.setup(); const { container } = renderApp("/play/"); await user.click(container.querySelector(".edit-players-button")!); await user.click(container.querySelector(".delete-button")!); - expect(screen.getByText("No players yet")).toBeTruthy(); - const hint = container.querySelector(".player-list-empty-hint")!; + expect(screen.getAllByText("No players yet")).toHaveLength(2); + const hint = container.querySelector(".edit-players-empty-hint")!; expect(hint.textContent).toBe("Press Add player to add one"); - expect(hint.querySelector(".player-list-empty-button")!.textContent).toBe("Add player"); + expect(hint.querySelector(".edit-players-empty-button")!.textContent).toBe("Add player"); await user.click(container.querySelector(".done-button")!); - expect(hint.textContent).toBe("Press Edit players to add some"); - expect(hint.querySelector(".player-list-empty-button")!.textContent).toBe("Edit players"); + const listHint = container.querySelector(".player-list-empty-hint")!; + expect(listHint.textContent).toBe("Press Edit players to add some"); + expect(listHint.querySelector(".player-list-empty-button")!.textContent).toBe("Edit players"); await user.click(container.querySelector(".edit-players-button")!); await user.click(container.querySelector(".add-player-button")!); expect(container.querySelector(".player-list-empty")).toBeNull(); + expect(container.querySelector(".edit-players-empty")).toBeNull(); }); it("copes with there being no players", async () => { const user = userEvent.setup(); const { container } = renderApp("/play/"); - await user.click(container.querySelector(".done-button, .edit-players-button")!); + await user.click(container.querySelector(".edit-players-button")!); await user.click(container.querySelector(".delete-button")!); expect(caption(container)).toBe("Round 1"); @@ -1588,13 +1830,14 @@ describe("labelled buttons", () => { expect(screen.getByRole("button", { name: "Next round" })).toBeTruthy(); }); - it("say what the edit button does now", async () => { + it("name the window that the edit button opens, with a Done button to close it", async () => { const user = userEvent.setup(); renderApp("/play/"); await user.click(screen.getByRole("button", { name: "Edit players" })); - expect(screen.getByRole("button", { name: "Done" })).toBeTruthy(); - expect(screen.queryByRole("button", { name: "Edit players" })).toBeNull(); + expect(screen.getByRole("dialog", { name: "Edit Players" })).toBeTruthy(); + await user.click(screen.getByRole("button", { name: "Done" })); + expect(screen.queryByRole("dialog")).toBeNull(); }); it("name the add player button, which only exists for assistive technology in edit mode", async () => { @@ -1616,10 +1859,6 @@ describe("labelled buttons", () => { await user.click(screen.getByRole("tab", { name: "Plot" })); // Not showing a round expect(screen.queryByRole("button", { name: "Next round" })).toBeNull(); expect(screen.queryByRole("button", { name: "Previous round" })).toBeNull(); - - await user.click(screen.getByRole("tab", { name: "Keypad" })); - await user.click(screen.getByRole("button", { name: "Edit players" })); // Editing, so no rounds - expect(screen.queryByRole("button", { name: "Next round" })).toBeNull(); }); }); }); @@ -1627,7 +1866,6 @@ describe("labelled buttons", () => { describe("focus after pressing a button", () => { // The browser draws a focus ring around a focused button as soon as a key (even Shift, for // scrolling sideways) is pressed, so a button that was only clicked must not stay focused. - const focusedLabel = () => document.activeElement?.getAttribute("aria-label"); it("is let go of when a button is clicked with the mouse", async () => { const user = userEvent.setup(); @@ -1651,7 +1889,7 @@ describe("focus after pressing a button", () => { ]; for (const find of buttons) { await user.click(find()); - expect(document.activeElement).toBe(document.body); + expect(document.activeElement instanceof HTMLButtonElement).toBe(false); } }); @@ -1695,7 +1933,6 @@ describe("focus after pressing a button", () => { await user.click(name); expect(document.activeElement).toBe(name); - expect(focusedLabel()).toBeNull(); }); }); @@ -1998,15 +2235,15 @@ describe("letting go of a pinned player by pressing elsewhere", () => { const { container } = renderApp("/play/"); await user.click(screen.getByRole("tab", { name: "Plot" })); - await user.click(container.querySelector(".game-name-label")!); + await user.click(container.querySelector(".plot-area")!); expect(container.querySelector(".player.pinned")).toBeNull(); }); }); -describe("flashing the row of a player whose score was updated", () => { +describe("bouncing the score of a player whose score was updated", () => { const flashing = (container: HTMLElement) => - Array.from(container.querySelectorAll(".player")).map( + Array.from(container.querySelectorAll(".player .score")).map( (row) => row.classList.contains("flash-a") || row.classList.contains("flash-b"), ); const enterScore = (score: string) => { @@ -2046,7 +2283,7 @@ describe("flashing the row of a player whose score was updated", () => { it("starts the flash over for a player who scores again, with a different animation", async () => { const { container } = await twoPlayers(); - const first = () => container.querySelectorAll(".player")[0]!; + const first = () => container.querySelectorAll(".player .score")[0]!; enterScore("5"); // Player 1 expect(first().classList.contains("flash-a")).toBe(true); @@ -2088,7 +2325,7 @@ describe("flashing the row of a player whose score was updated", () => { await user.keyboard("9{Enter}"); expect(before).toEqual([true, true]); - const rows = container.querySelectorAll(".player"); + const rows = container.querySelectorAll(".player .score"); expect(rows[1]!.classList.contains("flash-b")).toBe(true); // The second time for Player 2 expect(rows[0]!.classList.contains("flash-a")).toBe(true); // Still the first time for Player 1 }); @@ -2096,7 +2333,7 @@ describe("flashing the row of a player whose score was updated", () => { it("does not when the score is left as it was, or cancelled, or is not a number", async () => { const { user, container } = await onTheTable(); const classes = () => - Array.from(container.querySelectorAll(".player")).map((row) => row.className); + Array.from(container.querySelectorAll(".player .score")).map((row) => row.className); const before = classes(); await user.click(scoreButton(container, 0)); @@ -2131,7 +2368,7 @@ describe("flashing the row of a player whose score was updated", () => { it("does not flash when a player is selected by pressing them", async () => { const { user, container } = await twoPlayers(); - await user.click(container.querySelectorAll(".player")[1]!); + await user.click(container.querySelectorAll(".player .score")[1]!); expect(flashing(container)).toEqual([false, false]); }); @@ -2159,7 +2396,7 @@ describe("flashing the row of a player whose score was updated", () => { await user.click(screen.getByRole("button", { name: "Done" })); expect(() => enterScore("5")).not.toThrow(); - expect(container.querySelectorAll(".player")).toHaveLength(0); + expect(container.querySelectorAll(".player .score")).toHaveLength(0); }); }); }); diff --git a/web/src/components/FittedText.tsx b/web/src/components/FittedText.tsx deleted file mode 100644 index 00b94bd..0000000 --- a/web/src/components/FittedText.tsx +++ /dev/null @@ -1,56 +0,0 @@ -import { useLayoutEffect, useRef } from "react"; - -/** The smallest the text is made, below which a long name is cut off with "…" instead */ -const MIN_FONT_SIZE_PX = 13; - -/** - * Text that gets smaller when it would otherwise be too big for the box it is in, rather than being - * cut off. It is as big as the stylesheet makes it unless that doesn't fit. - * - * The box is the text's own element, which the stylesheet has to give a size to fit (by letting it - * shrink, and hiding what overflows) rather than one that grows to suit the text. - */ -export function FittedText({ text, className }: { text: string; className?: string }) { - const ref = useRef(null); - - useLayoutEffect(() => { - const element = ref.current; - if (!element) return; - const el: HTMLSpanElement = element; - - // A couple of pixels of leeway on the height, as the lines of text are rounded and the descenders - // of the last one can hang a little past the box. A whole extra line is a lot more than that. - const overflows = () => - el.scrollWidth > el.clientWidth + 1 || el.scrollHeight > el.clientHeight + 3; - - function fit() { - el.style.fontSize = ""; // Back to the size that the stylesheet gives it, to start from - let size = parseFloat(getComputedStyle(el).fontSize); - while (size > MIN_FONT_SIZE_PX && overflows()) { - size -= 1; - el.style.fontSize = `${size}px`; - } - } - - fit(); - // The size of the text depends on the font, which may not have loaded yet - let cancelled = false; - void document.fonts?.ready.then(() => { - if (!cancelled) fit(); - }); - // The space changes with the window, and when the layout changes. Its parent is watched, as - // the text itself is not what decides how big the space is. - const observer = new ResizeObserver(fit); - if (el.parentElement) observer.observe(el.parentElement); - return () => { - cancelled = true; - observer.disconnect(); - }; - }, [text]); - - return ( - - {text} - - ); -} diff --git a/web/src/components/game-play-page/GamePlayPage.scss b/web/src/components/game-play-page/GamePlayPage.scss index 1d731de..16bb888 100644 --- a/web/src/components/game-play-page/GamePlayPage.scss +++ b/web/src/components/game-play-page/GamePlayPage.scss @@ -1,3 +1,4 @@ +@use "sass:color"; @use "../../Colors.scss" as *; @use "../../Breakpoints.scss" as *; @@ -7,6 +8,16 @@ $left-width: clamp(420px, 38vw, 500px); // How much the tabs curve where they meet the main panel $tab-flare: 8px; +// The column of tabs beside the player list, which the header stops short of +$tabs-width: 90px; + +// The sizes of what is stacked, which the size of the panel is worked out from (see .content-inner) +$stacked-header-height: 64px; +$stacked-tabs-height: 56px; +$stacked-gap: 10px; + +$done-color: color.mix($light-elements, $gray-3, 75%); // The same as the Enter key + .game-play-background { display: flex; align-items: center; @@ -26,29 +37,26 @@ $tab-flare: 8px; .top-left-section { flex: none; // Keep its height, however long the player list gets - width: 100%; - height: 100px; + width: calc(100% - $tabs-width); // To end where the player list does, not where the tabs do + height: 45px; display: flex; gap: 10px; - // Just the Home button, as tall as the header, which is as tall as the outline of the game name + // Home, the button for editing the players (or finishing), then fullscreen, side by side .top-buttons-section { - width: 80px; + flex: 1; + min-width: 0; display: flex; - flex-direction: column; gap: 10px; button { - flex: 1; display: flex; align-items: center; - justify-content: flex-start; // Over towards the edge of the screen, which is where back is + justify-content: center; background-color: $gray-1; border: 1px solid $gray-4; - border-left: 0; - border-top-right-radius: 16px; - border-bottom-right-radius: 16px; - color: rgba($light-elements, 0.55); // Both icons, which are quiet, as it is not used much + border-radius: 16px; + color: rgba($light-elements, 0.55); // The icons are quiet, as they are not used much cursor: pointer; &:hover { @@ -68,93 +76,54 @@ $tab-flare: 8px; } } - // Fullscreen, under Home. Smaller icon and centered, as it is not about going back. + // Over towards the edge of the screen, which is where back is + .button-home { + flex: none; + width: 80px; + justify-content: flex-start; + border-left: 0; + border-top-left-radius: 0; + border-bottom-left-radius: 0; + } + + // Smaller icon, as it is not about going back .button-fullscreen { - justify-content: center; + flex: none; + width: 56px; span { font-size: 28px; } } - } - - .game-name-section { - position: relative; - flex: 1; - min-width: 0; - margin-right: 10px; - background-color: $gray-1; - border: 1px solid $gray-4; - border-radius: 16px; - display: flex; - align-items: center; - justify-content: center; - - // While the name is being edited, the panel stays the shade that it was when it was pointed - // at to start, so that there is no change of color as the text box replaces the name - &.editing { - background-color: $gray-2; - } - // The name, which is pressed to rename the game - .game-name-label { - position: relative; - width: 100%; - height: 100%; + .edit-players-button, + .done-button { + flex: 1; min-width: 0; - padding: 0 16px 3px; - display: flex; - align-items: center; - justify-content: center; - background: none; - border: 0; - border-radius: 15px; - color: $light-elements; - cursor: pointer; + gap: 8px; font-family: inherit; - font-size: 22pt; - font-weight: bold; - touch-action: manipulation; - -webkit-tap-highlight-color: transparent; - transition: background-color 60ms ease; - - .game-name-text { - min-width: 0; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; - } - - @media (hover: hover) { - &:hover { - background-color: $gray-2; - } - } + font-size: 15px; + font-weight: 600; + white-space: nowrap; - // No lighter shade for pressing: the name turns into a text box as soon as it is pressed, - // and it has to carry on looking the same through that, or it flickers - &:focus-visible { - outline: 2px solid $light-elements; - outline-offset: -4px; + span { + font-size: 22px; } } - .game-name-input { - background-color: $gray-3; - width: calc(100% - 20px); - min-width: 0; // Don't let the input's intrinsic width resize the layout - padding: 0 8px 3px; - border: 1px solid $gray-5; - border-radius: 8px; - color: $light-elements; - font-family: inherit; - font-size: 22pt; - font-weight: bold; - text-align: center; + // The way out of editing, so it is as prominent as the Enter key of the keypad + .done-button { + background-color: $done-color; + border-color: $done-color; + color: $background; + + &:hover { + background-color: $done-color; + filter: brightness(0.94); + } - &:focus { - outline: none; - border-color: $light-elements; + &:active { + filter: brightness(0.85); } } } @@ -173,23 +142,17 @@ $tab-flare: 8px; display: flex; // The round buttons and the add player button stay put, the list scrolls flex-direction: column; overflow: hidden; - position: relative; // For the button that expands it, in the corner background-color: $gray-1; border: 1px solid $gray-4; border-left: 0; border-top-right-radius: 16px; border-bottom-right-radius: 16px; - - // Only for the stacked layout, where there is room below to grow into - .expand-list-button { - display: none; - } } // The tabs for the keypad, the plot and the table. Side by side, they hang off the left edge // of the content, and the selected one joins up with it. .buttons-section { - flex: 0 0 90px; + flex: 0 0 $tabs-width; height: 90%; display: flex; flex-direction: column; @@ -229,7 +192,7 @@ $tab-flare: 8px; // corner. The other tabs have square corners where they meet the panel's line. Each curve is // a small square, filled where the corner is, and drawn with the same line as the outline. &.selected { - width: 73px; + width: 76px; margin-right: -1px; z-index: 2; @@ -270,15 +233,59 @@ $tab-flare: 8px; } } - &:hover:not(.selected) { - background-color: $gray-3; + // Only for a mouse. On a touchscreen :hover stays on what was tapped, which for the tab that + // was just pressed to drop it would leave it looking like it is still being pointed at. + @media (hover: hover) { + &:hover:not(.selected) { + background-color: $gray-3; + } } } } } } +// Fills the panel, whatever it holds. When the panel changes to another, either the new one slides up +// over the one that it replaces, or the old one drops away to uncover the new one, which are why each +// has a background of its own. +.content-inner { + position: absolute; + inset: 0; + z-index: 1; + background-color: $gray-1; + + &.entering { + z-index: 2; + animation: content-slide-up 250ms ease-out; + } + + &.dropping { + z-index: 2; + animation: content-drop-down 250ms ease-in forwards; + } +} + +@keyframes content-drop-down { + to { + transform: translateY(100%); + } +} + +@keyframes content-slide-up { + from { + transform: translateY(100%); + } +} + +@media (prefers-reduced-motion: reduce) { + .content-inner.entering, + .content-inner.dropping { + animation: none; + } +} + .content-section { + position: relative; flex: 1; min-width: 0; height: 90%; @@ -287,6 +294,9 @@ $tab-flare: 8px; border-right: none; border-top-left-radius: 16px; border-bottom-left-radius: 16px; + // What is in it is cut off at its rounded corners (inside its border), rather than being drawn over + // them, and a tab sliding over another is not to be seen outside it + overflow: hidden; } // On portrait screens everything is stacked: the header, the list, the content, then the tabs @@ -294,11 +304,15 @@ $tab-flare: 8px; .game-play-background { display: grid; grid-template-columns: minmax(0, 1fr); - grid-template-rows: auto minmax(160px, 36%) minmax(0, 1fr) auto; - gap: 10px; + grid-template-rows: auto 36fr 64fr auto; + transition: + transform 150ms ease-out, + grid-template-rows 250ms ease; + gap: $stacked-gap; // More room above and below than at the sides, as a phone's screen has rounded corners padding: 28px 12px; align-items: stretch; + container-type: size; // For working out how tall the panel will be, see .content-inner } // The columns are only there to arrange things side by side. Take them out of the way, so that @@ -310,45 +324,28 @@ $tab-flare: 8px; .left-section .top-left-section { grid-row: 1; - height: 64px; + width: 100%; // There are no tabs beside the list here + height: $stacked-header-height; .top-buttons-section { - width: auto; - flex-direction: row; - - button { - flex: none; - width: 64px; + .button-home { + width: 76px; + justify-content: center; border-left: 1px solid $gray-4; border-radius: 16px; } .button-fullscreen { - width: 48px; - } - } - - .game-name-section { - margin-right: 0; - - .game-name-label, - .game-name-input { - font-size: 18pt; + width: 60px; } - // The name can take two lines, so that more of a long one fits on a narrow screen - .game-name-label { - padding: 0 12px; - } + // There is room for it to be bigger + .edit-players-button { + font-size: 17px; - .game-name-label .game-name-text { - display: -webkit-box; - -webkit-box-orient: vertical; - -webkit-line-clamp: 2; - font-size: 16pt; - line-height: 1.15; - text-align: center; - white-space: normal; + span { + font-size: 24px; + } } } } @@ -363,7 +360,7 @@ $tab-flare: 8px; button { flex: 1; width: auto; - height: 56px; + height: $stacked-tabs-height; margin-right: 0; border: 1px solid $gray-4; border-radius: 16px; @@ -405,66 +402,6 @@ $tab-flare: 8px; grid-row: 2; border-left: 1px solid $gray-4; border-radius: 16px; - - // Small, in the lower right, and over the list rather than taking room from it. Styled like the - // Edit players button: quiet until it is pointed at. - .expand-list-button { - position: absolute; - right: 10px; - bottom: 10px; - z-index: 1; - width: 44px; - height: 44px; - display: flex; - align-items: center; - justify-content: center; - background-color: $gray-1; - border: 1px solid $gray-3; - border-radius: 12px; - color: rgba($light-elements, 0.45); - cursor: pointer; - touch-action: manipulation; - -webkit-tap-highlight-color: transparent; - transition: - transform 60ms ease, - background-color 60ms ease, - border-color 60ms ease, - color 60ms ease; - - @media (hover: hover) { - &:hover:not(:active) { - background-color: $gray-2; - border-color: $gray-5; - color: $light-elements; - } - } - - &:active { - transform: scale(0.94); - background-color: $gray-4; - } - - &:focus-visible { - outline: 2px solid $light-elements; - outline-offset: 2px; - } - - // Two chevrons pointing down, overlapping so that they read as one icon - .double-chevron { - display: flex; - flex-direction: column; - align-items: center; - - .material-symbols-outlined { - font-size: 22px; - transform: rotate(90deg); - - + .material-symbols-outlined { - margin-top: -13px; - } - } - } - } } } @@ -473,20 +410,78 @@ $tab-flare: 8px; height: auto; border-right: 1px solid $gray-4; border-radius: 16px; + overflow: hidden; // So that its contents do not show outside it while it changes size } - // The list takes the main panel's place, which stays where it is but out of sight - .list-expanded { + // The panel changes size as the list gives it room and takes it back, and what is in it does not: + // it is the size that the panel is going to be, and the panel shows as much of it as it has room + // for. It is kept to the bottom of the panel, which is the edge that stays where it is (the top is + // what moves), so what is in it stays still on the screen as the panel grows or shrinks around it, + // whether it is being covered by another tab, or by the list, or is uncovered. That size is worked out from the room that there is + // (the height of the page, less what is not shared out between them), as the panel takes 64 + // hundredths of it when it is beside the list, or all of it (and the gap above) for the table. + $shared-room: calc(100cqh - $stacked-header-height - $stacked-tabs-height - 3 * $stacked-gap); + .content-inner { + top: auto; + bottom: 0; + height: calc($shared-room * 0.64 - 2px); // Less the panel's border + + &.is-table { + height: calc($shared-room + $stacked-gap - 2px); + } + } + + // The list and the panel share the room between them, as fractions of a hundred that add up to the + // same each time (so that nothing is lost in between), and give it to each other by changing + // them: all of it to the table, which has the players in its own headings, or all of it to the + // list, when it is expanded. Changing them is animated, here and by the margins below. Whichever + // has no room left is hidden once it has finished going (which is why that is delayed). + .content-section, + .left-section .bottom-left-section .player-list-section { + min-height: 0; // To be able to go all the way down to nothing + transition: margin 250ms ease; + } + + .table-showing:not(.list-expanded) { + grid-template-rows: auto 0fr 100fr auto; + + .content-section { + margin-top: -10px; // The gap that the list's row has above it is not wanted either + } + .left-section .bottom-left-section .player-list-section { - grid-row: 2 / 4; + visibility: hidden; + transition: + margin 250ms ease, + visibility 0s linear 250ms; + } + } - .expand-list-button .double-chevron { - transform: rotate(180deg); // Pointing up: shrink - } + .list-expanded { + grid-template-rows: auto 100fr 0fr auto; + + .left-section .bottom-left-section .player-list-section { + margin-bottom: -10px; // And the gap that the panel's row has below it } .content-section { - display: none; + visibility: hidden; + transition: + margin 250ms ease, + visibility 0s linear 250ms; + } + } + + // The list is not to grow a scroll bar as it shrinks, for the moment that it has too little room + .resizing .player-list { + overflow-y: hidden; + } + + @media (prefers-reduced-motion: reduce) { + .game-play-background, + .content-section, + .left-section .bottom-left-section .player-list-section { + transition: none !important; } } } @@ -499,13 +494,6 @@ $tab-flare: 8px; } .left-section .top-left-section { - height: 76px; - - .game-name-section { - .game-name-label, - .game-name-input { - font-size: 18pt; - } - } + height: 33px; } } diff --git a/web/src/components/game-play-page/GamePlayPage.tsx b/web/src/components/game-play-page/GamePlayPage.tsx index 76761e1..a19f674 100644 --- a/web/src/components/game-play-page/GamePlayPage.tsx +++ b/web/src/components/game-play-page/GamePlayPage.tsx @@ -3,9 +3,10 @@ import clsx from "clsx"; import { useCallback, useEffect, useRef, useState } from "react"; import { useLocation, useNavigate } from "react-router-dom"; import { useGame } from "@/GameContext"; -import { FittedText } from "@/components/FittedText"; +import { useToast } from "@/ToastContext"; import { lastRound } from "@/utils/Scores"; import { runWithTransition, usePageAppeared } from "@/viewTransition"; +import { EditPlayersDialog } from "./edit-players-dialog/EditPlayersDialog"; import { EnterScoresComponent } from "./enter-scores-component/EnterScoresComponent"; import { PlayerListComponent } from "./player-list-component/PlayerListComponent"; import { PlotScoresComponent } from "./plot-scores-component/PlotScoresComponent"; @@ -13,6 +14,20 @@ import { ScoreTableComponent } from "./score-table-component/ScoreTableComponent import { useKeepAboveKeyboard } from "@/useKeepAboveKeyboard"; import { FullscreenButton } from "@/components/FullscreenButton"; +/** How long a tab takes to slide up over the one before it, or to drop away from in front of one */ +const SLIDE_MS = 250; + +/** Whether things are to be moved about, rather than just changed */ +function motionAllowed(): boolean { + return ( + typeof window.matchMedia === "function" && + !window.matchMedia("(prefers-reduced-motion: reduce)").matches + ); +} + +/** How long the player list takes to change size (a little longer than the stylesheet says) */ +const RESIZE_MS = 300; + type Content = "keypad" | "plot" | "table"; const contentButtons: { content: Content; icon: string; label: string }[] = [ @@ -24,16 +39,51 @@ const contentButtons: { content: Content; icon: string; label: string }[] = [ export function GamePlayPage() { const navigate = useNavigate(); usePageAppeared(); - // "Start New Game" opens this page already in edit mode so the players can be set up - const startInEditMode = (useLocation().state as { newGame?: boolean } | null)?.newGame === true; + // "Start New Game" opens this page with the window for editing the players already open, so that + // they can be set up + const location = useLocation(); + const startInEditMode = (location.state as { newGame?: boolean } | null)?.newGame === true; + // Whether the window opened by itself, for a new game. Kept from then until it is closed, as the + // address still says it is a new game for as long as the page is there. + const [forNewGame, setForNewGame] = useState(startInEditMode); + // And not for as long as the history says so: going back to this page, or reloading it, is not a + // new game + useEffect(() => { + if (startInEditMode) navigate(location.pathname, { replace: true, state: null }); + }, [startInEditMode, navigate, location.pathname]); const { game, updateGame } = useGame(); + const { dismissAll } = useToast(); useKeepAboveKeyboard(); + // What the panel holds. With the list on its own (below), it still holds what it did, out of sight. const [currentContent, setCurrentContent] = useState("keypad"); // On a stacked layout, the list can grow down over the space of the main panel const [listExpanded, setListExpanded] = useState(false); + // The tab that is selected, which is none while the list is on its own. That is a state of its own, + // before the first tab: it is not the tab that the panel was holding, with the list over it. + const tab: Content | null = listExpanded ? null : currentContent; const [selectedPlayerIdState, setSelectedPlayerId] = useState(""); // Continuing a game picks up at its latest round; a new game starts at round 1 const [currentRound, setCurrentRound] = useState(() => Math.max(1, lastRound(game))); + // How the panel is changing, for as long as that takes. The list on its own counts as the first of + // the tabs, before the keypad. Going to a tab that is further along, the new one slides up ("up", + // over the one it replaces, or "in", from there being none). Going to one before, the old one + // drops away ("drop", which uncovers the one it replaced, or "out", which uncovers the list). + const [slide, setSlide] = useState<{ + leaving: Content | null; + kind: "up" | "drop" | "in" | "out"; + } | null>(null); + const leavingContent = slide?.leaving ?? null; + const slideTimer = useRef>(undefined); + useEffect(() => () => clearTimeout(slideTimer.current), []); + function startSlide(next: NonNullable) { + setSlide(next); + clearTimeout(slideTimer.current); + slideTimer.current = setTimeout(() => setSlide(null), SLIDE_MS + 50); + } + const [resizing, setResizing] = useState(false); + const resizeTimer = useRef>(undefined); + useEffect(() => () => clearTimeout(resizeTimer.current), []); + // Whether the window for editing the players is open const [editing, setEditing] = useState(startInEditMode); // The plot emphasizes the line of the player the mouse is over in the player list, or failing // that, of the one that was tapped (which is the only way to do it without a mouse) @@ -41,13 +91,6 @@ export function GamePlayPage() { const [pinnedPlayerIdState, setPinnedPlayerId] = useState(""); // How many times each player's row has been made to flash, which the row restarts its flash by const [flashCounts, setFlashCounts] = useState>({}); - // The game name is edited on its own, by pressing it, whether or not the players are being edited. - // A new game starts with its name being edited, ready to be typed over. - const [editingName, setEditingName] = useState(startInEditMode); - const nameBeforeEditing = useRef(game.name); - // Whether the name should be selected when its text box appears, which is only the first time - const selectGameName = useRef(startInEditMode); - const gameNameRef = useRef(null); const playerListRef = useRef(null); // Fall back to the first player if the selected player doesn't exist (e.g. it was deleted) @@ -56,7 +99,7 @@ export function GamePlayPage() { ? selectedPlayerIdState : firstPlayerId; - const pinnedPlayerId = currentContent === "plot" && !editing ? pinnedPlayerIdState : ""; + const pinnedPlayerId = tab === "plot" && !editing ? pinnedPlayerIdState : ""; const highlightedPlayerId = hoveredPlayerId || pinnedPlayerId; // What the keypad says the score being typed is for @@ -66,54 +109,14 @@ export function GamePlayPage() { ? `${selectedPlayer.playerName.trim() || "Player"} · ${roundName}` : roundName; - // When leaving edit mode, go back to the first player + // However the window is closed, go back to the first player. Deletions were meant, so there is no + // more need to offer to undo them. const exitEditMode = useCallback(() => { + dismissAll(); setEditing(false); + setForNewGame(false); setSelectedPlayerId(firstPlayerId); - }, [firstPlayerId]); - - // Exit edit mode if user clicks anywhere other than the game name or the player list (which has - // the buttons for starting and finishing editing in it) - useEffect(() => { - if (!editing) return; - - function onPointerDown(event: PointerEvent) { - const target = event.target as Node; - // Pressing a toast (like Undo, after deleting a player) is part of editing, not leaving it - if (target instanceof Element && target.closest(".toasts")) return; - // Likewise the color picker, which is in the body, not the player list, but is part of editing - if (target instanceof Element && target.closest(".color-select-background")) return; - if (!gameNameRef.current?.contains(target) && !playerListRef.current?.contains(target)) { - exitEditMode(); - } - } - - document.addEventListener("pointerdown", onPointerDown); - return () => document.removeEventListener("pointerdown", onPointerDown); - }, [editing, exitEditMode]); - - // Pressing Enter while editing, with no name being edited, means the editing is done - useEffect(() => { - if (!editing) return; - - function onKeyDown(event: KeyboardEvent) { - if (event.key !== "Enter" || event.repeat) return; // Not the Enter of a key held down - if (event.ctrlKey || event.metaKey || event.altKey || event.shiftKey) return; - - // Where the key was pressed, not where the focus is now: Enter in a name box takes the focus - // out of it, and that Enter has done its job by doing that. On a button, Enter presses it. - const target = event.target; - if (target instanceof Element && target.closest("input, textarea, select, button")) return; - - // The color picker has its own idea of what is going on - if (document.querySelector(".color-select-background")) return; - - exitEditMode(); - } - - window.addEventListener("keydown", onKeyDown); - return () => window.removeEventListener("keydown", onKeyDown); - }, [editing, exitEditMode]); + }, [dismissAll, firstPlayerId]); // Let go of a pinned player when pressing anywhere, other than on a button (a tab, say, which can // decide for itself whether to let go) or a player, which pins or unpins them as it is pressed @@ -146,11 +149,38 @@ export function GamePlayPage() { // Pressing a player selects them for entering scores, and on the plot, picks out their line function onPlayerPressed(playerId: string) { setSelectedPlayerId(playerId); - if (currentContent === "plot" && !editing) { + if (tab === "plot" && !editing) { setPinnedPlayerId(pinnedPlayerId === playerId ? "" : playerId); } } + // The list changes size with the tabs (when stacked), which takes a moment, and for that moment it + // is not to have a scroll bar come and go + function noteResize() { + setResizing(true); + clearTimeout(resizeTimer.current); + resizeTimer.current = setTimeout(() => setResizing(false), RESIZE_MS); + } + + // Where the tabs are along the bottom, with the list above the panel rather than beside it + function isStackedLayout() { + return window.matchMedia?.("(max-aspect-ratio: 1 / 1)").matches ?? false; + } + + // Pressing the tab that is showing, when stacked, drops it and lets the list have its panel's place + function pressTab(content: Content) { + noteResize(); + if (content === tab && isStackedLayout()) { + setListExpanded(true); + // Showing the totals, as for the plot and the table + setPinnedPlayerId(""); + updateGame({ type: "trim_scores" }); + if (motionAllowed()) startSlide({ leaving: null, kind: "out" }); + return; + } + changeContent(content); + } + function changeContent(content: Content) { setListExpanded(false); if (content !== "plot") setPinnedPlayerId(""); @@ -158,29 +188,38 @@ export function GamePlayPage() { // Delete any trailing rounds that are all zeros updateGame({ type: "trim_scores" }); } - if (content === "keypad" && currentContent !== "keypad") { + if (content === "keypad" && tab !== "keypad") { // When we switch to the keypad, automatically go to the next round const newRound = lastRound(game) + 1; updateGame({ type: "add_round", round: newRound }); setCurrentRound(newRound); setSelectedPlayerId(firstPlayerId); } + // Only when stacked: beside the list, a tab is just changed + if (motionAllowed() && isStackedLayout()) { + if (listExpanded) { + startSlide({ leaving: null, kind: "in" }); + } else if (content !== currentContent) { + const forward = + contentButtons.findIndex((button) => button.content === content) > + contentButtons.findIndex((button) => button.content === currentContent); + startSlide({ leaving: currentContent, kind: forward ? "up" : "drop" }); + } + } setCurrentContent(content); } - function startEditingName() { - nameBeforeEditing.current = game.name; - selectGameName.current = true; - setEditingName(true); - } - - function finishEditingName() { - setEditingName(false); - // A game with no name at all would leave nothing to press to name it again - if (game.name.trim() === "") { - updateGame({ type: "update_name", newName: nameBeforeEditing.current }); - } - } + // The list is only ever on its own when the tabs are along the bottom, so if that stops being so + // (the screen is turned, or its window made wider), the tab that the panel holds is selected again + useEffect(() => { + const query = window.matchMedia?.("(max-aspect-ratio: 1 / 1)"); + if (!query) return; + const onChange = () => { + if (!query.matches) setListExpanded(false); + }; + query.addEventListener?.("change", onChange); + return () => query.removeEventListener?.("change", onChange); + }, []); // Select the player `offset` places after the selected one, wrapping around the list function stepPlayer(offset: number) { @@ -199,117 +238,14 @@ export function GamePlayPage() { setCurrentRound(Math.max(0, currentRound - 1)); } - return ( -
-
-
-
- - -
-
- {editingName ? ( - { - if (el && selectGameName.current) { - selectGameName.current = false; - el.focus(); - el.select(); - } - }} - value={game.name} - onChange={(e) => updateGame({ type: "update_name", newName: e.target.value })} - onBlur={finishEditingName} - onKeyDown={(e) => { - if (e.key === "Enter") e.currentTarget.blur(); - if (e.key === "Escape") { - updateGame({ type: "update_name", newName: nameBeforeEditing.current }); - e.currentTarget.blur(); - } - }} - /> - ) : ( - - )} -
-
-
-
- setEditing(true)} - onFinishEditing={exitEditMode} - /> - {/* Not with the keypad, which needs the list beside it to pick who the score is for */} - {currentContent !== "keypad" && ( - - )} -
-
- {contentButtons.map(({ content, icon, label }) => ( - - ))} -
-
-
-
- {currentContent === "keypad" && ( + function renderContent(content: Content) { + switch (content) { + case "keypad": + return ( { saveScore(score); stepPlayer(1); @@ -319,12 +255,107 @@ export function GamePlayPage() { onNextRound={nextRound} onPrevRound={prevRound} /> - )} - {currentContent === "plot" && ( - - )} - {currentContent === "table" && } + ); + case "plot": + return ; + case "table": + return ; + } + } + + return ( + <> +
+
+
+
+ + + +
+
+
+
+ +
+
+ {contentButtons.map(({ content, icon, label }) => ( + + ))} +
+
+
+
+ {/* Each has its own size, whatever size the panel is made, so that it slides rather than + stretches */} + {contentButtons.map(({ content }) => + content === currentContent || content === leavingContent ? ( +
+ {renderContent(content)} +
+ ) : null, + )} +
-
+ {/* Outside the page, as the page is moved up out of the way of the keyboard, and it is not */} + {editing && } + ); } diff --git a/web/src/components/game-play-page/edit-players-dialog/EditPlayersDialog.scss b/web/src/components/game-play-page/edit-players-dialog/EditPlayersDialog.scss new file mode 100644 index 0000000..bd832c0 --- /dev/null +++ b/web/src/components/game-play-page/edit-players-dialog/EditPlayersDialog.scss @@ -0,0 +1,261 @@ +@use "sass:color"; +@use "../../../Colors.scss" as *; +@use "../../../Breakpoints.scss" as *; + +$row-height: 40px; // Tall enough to tap +$player-gap: 8px; +// Empty space above the first player and below the last, inside the scrolling list. A player being +// dragged can be pulled a little past either end, and the list would cut it off without this. +$drag-room: 10px; +$done-color: color.mix($light-elements, $gray-3, 75%); // The same as the Enter key + +@keyframes edit-players-backdrop-in { + from { + background-color: rgba(black, 0); + } +} + +@keyframes edit-players-dialog-in { + from { + opacity: 0; + } +} + +// Over the whole page, and under the color picker and the toasts, which have to be seen over it +.edit-players-backdrop { + position: fixed; + inset: 0; + z-index: 2; + display: flex; + align-items: center; + justify-content: center; + background-color: rgba(black, 0.75); + animation: edit-players-backdrop-in 0.2s ease; + + @media (prefers-reduced-motion: reduce) { + &, + .edit-players-dialog { + animation: none; + transition-duration: 0s; + } + } +} + +.edit-players-dialog { + width: min(440px, calc(100% - 32px)); + // --shift and --fit-height are set by the component, to keep clear of a phone's keyboard + max-height: min(calc(100% - 48px), var(--fit-height, 100%)); + padding: 24px 24px 20px; + display: flex; + flex-direction: column; + background-color: $gray-1; + border: 1px solid $gray-4; + border-radius: 24px; + color: $light-elements; + animation: edit-players-dialog-in 0.2s ease; + transform: translateY(var(--shift, 0px)); + transition: transform 0.15s ease-out; + + &:focus { + outline: none; + } + + @include small-screen { + max-height: min(calc(100% - 24px), var(--fit-height, 100%)); + padding: 18px 16px 16px; + } + + .edit-players-title { + flex: none; + margin: 0 0 12px; + font-size: 18pt; + font-weight: 700; + text-align: center; + } + + // Scrolls when there are more players than fit + .edit-players-list { + flex: 0 1 auto; + min-height: 0; + margin: 0 -8px; + padding: $drag-room 8px; + overflow-x: hidden; + overflow-y: auto; + scrollbar-width: thin; + scrollbar-color: $gray-5 transparent; + display: flex; + flex-direction: column; + gap: $player-gap; + } + + // What the list says when there is nobody in it + .edit-players-empty { + padding: 16px 0; + color: rgba($light-elements, 0.55); + text-align: center; + + .edit-players-empty-title { + font-size: 16pt; + font-weight: bold; + } + + .edit-players-empty-hint { + margin-top: 6px; + font-size: 11pt; + } + + .edit-players-empty-button { + color: $light-elements; + font-weight: bold; + } + } + + .edit-player { + position: relative; + flex: none; // Rows keep their height instead of being squashed to fit + height: $row-height; + display: flex; + align-items: center; + gap: 10px; + transition: transform 150ms ease; + + &.dragging { + z-index: 1; + background-color: $gray-2; + box-shadow: 0 0 6px 0 black; + transition: none; + } + } + + .drag-handle { + flex: none; + align-self: stretch; + width: $row-height; + display: flex; + align-items: center; + justify-content: center; + color: $light-elements; + cursor: grab; + touch-action: none; // Or a finger dragging it would scroll the list instead, and cancel the drag + } + + .edit-player.dragging .drag-handle { + cursor: grabbing; + } + + .player-color { + flex: none; + align-self: stretch; + width: $row-height; + border-radius: 2px; + cursor: pointer; + } + + .player-name-input { + flex: 1; + width: 0; // Size comes from flex-grow only, not the input's intrinsic width + min-width: 0; + height: 32px; + padding: 0 8px; + background-color: $gray-3; + border: 1px solid $gray-5; + border-radius: 8px; + color: $light-elements; + font-family: inherit; + font-size: 18pt; + font-weight: bold; + + &:focus { + outline: none; + border-color: $light-elements; + } + } + + .delete-button { + flex: none; + align-self: stretch; + width: $row-height; + display: flex; + align-items: center; + justify-content: center; + color: $light-elements; + cursor: pointer; + } + + .edit-players-footer { + flex: none; + margin-top: 12px; + display: flex; + justify-content: center; + gap: 12px; + + button { + min-height: 44px; + padding: 0 20px 0 14px; + display: flex; + align-items: center; + gap: 8px; + border-radius: 12px; + cursor: pointer; + font-family: inherit; + font-size: 15px; + font-weight: 600; + touch-action: manipulation; + -webkit-tap-highlight-color: transparent; + transition: + transform 60ms ease, + background-color 60ms ease, + border-color 60ms ease, + color 60ms ease; + + &:active { + transform: scale(0.94); + } + + &:focus-visible { + outline: 2px solid $light-elements; + outline-offset: 2px; + } + + .material-symbols-outlined { + font-size: 22px; + } + } + + // An empty place for another player: a dashed outline that fills in when it is pointed at + .add-player-button { + background-color: transparent; + border: 2px dashed $gray-5; + color: rgba($light-elements, 0.75); + + @media (hover: hover) { + &:hover { + border-color: $light-elements; + color: $light-elements; + } + } + + &:active { + border-color: $light-elements; + color: $light-elements; + } + } + + // The way out, so it is as prominent as the Enter key of the keypad + .done-button { + background-color: $done-color; + border: 1px solid $done-color; + color: $background; + + @media (hover: hover) { + &:hover { + filter: brightness(0.94); + } + } + + &:active { + filter: brightness(0.85); + } + } + } +} diff --git a/web/src/components/game-play-page/edit-players-dialog/EditPlayersDialog.tsx b/web/src/components/game-play-page/edit-players-dialog/EditPlayersDialog.tsx new file mode 100644 index 0000000..2118540 --- /dev/null +++ b/web/src/components/game-play-page/edit-players-dialog/EditPlayersDialog.tsx @@ -0,0 +1,517 @@ +import "./EditPlayersDialog.scss"; +import clsx from "clsx"; +import React, { useEffect, useLayoutEffect, useRef, useState } from "react"; +import { useGame } from "@/GameContext"; +import { useToast } from "@/ToastContext"; +import { nextPlayerColor, type Scorecard } from "@/Game"; +import { autoScrollSpeed } from "@/utils/autoScroll"; +import { fitShift } from "@/utils/fitInView"; +import { newId } from "@/utils/newId"; +import { SelectColorComponent } from "../player-list-component/SelectColorComponent/SelectColorComponent"; + +/** How much of the screen has to be covered before it is taken to be a keyboard */ +const MIN_KEYBOARD_HEIGHT = 120; + +/** The room to leave between the window and the edge of what the keyboard leaves visible */ +const KEYBOARD_GAP = 12; + +/** + * A window over the game page for changing the players: renaming, recoloring, reordering, adding + * and deleting them. It is not the browser's own dialog, as that would put the color picker and the + * toasts (which offer to undo a deletion) underneath it. Closed with Done or Escape, and not by a + * press on the page behind, which would lose a half-made change too easily. With `selectFirstName`, as when a new game has just started, the first name is + * selected, ready to be typed over. + */ +export function EditPlayersDialog({ + onClose, + selectFirstName = false, +}: { + onClose: () => void; + selectFirstName?: boolean; +}) { + const { game, updateGame } = useGame(); + const { showToast } = useToast(); + const dialogRef = useRef(null); + // The player whose name field should be focused as soon as it appears (a just-added player) + // On a phone the keyboard is kept up the whole time, so one of the names always has the focus + const [touchDevice] = useState(() => window.matchMedia?.("(pointer: coarse)").matches ?? false); + const focusPlayerId = useRef( + selectFirstName || touchDevice ? (game.scorecards[0]?.id ?? "") : "", + ); + // Whether the name that is focused as the window opens is left alone, as opposed to selected. A + // tap that brings up the keyboard would not select it, and selecting it takes the phone's menu. + const leaveFirstNameAlone = useRef(touchDevice && !selectFirstName); + const lastNameBox = useRef(null); + const pickerOpen = useRef(false); + const addButtonRef = useRef(null); + // Whether a name has just been focused by a press, whose release would move the cursor into it and + // so undo the selecting of the whole name + const keepNameSelected = useRef(false); + // What kind of pointer pressed the name that has the focus, if one did. A selection made by a + // finger's tap brings up the phone's own menu (cut, copy, paste) and handles, which is not wanted. + const pressedWith = useRef(""); + const [selectingColorId, setSelectingColorId] = useState(""); + const [colorPickerPosition, setColorPickerPosition] = useState(null); + const [dragId, setDragId] = useState(""); + const listRef = useRef(null); + // While dragging, positions are measured down the whole list, scrolled out of view or not: the + // pointer's Y plus how far the list has scrolled. Then scrolling the list under a pointer that's + // standing still moves the dragged player along with it. + const dragStartY = useRef(0); + const pointerY = useRef(0); // The latest position of the pointer on the screen, while dragging + const [dragDeltaY, setDragDeltaY] = useState(0); + const [playerSpacing, setPlayerSpacing] = useState(0); + const playerRefs = useRef>(new Map()); + const playerPositions = useRef>(new Map()); + + // Takes the focus, so that the keyboard is for this window and not for the page behind it, unless + // a name box has taken it already + useEffect(() => { + const dialog = dialogRef.current; + if (dialog && !dialog.contains(document.activeElement)) dialog.focus(); + }, []); + + // The window sits in the middle of the screen. When a phone's keyboard comes up and would cover + // some of it, it moves up out of the way, and makes itself smaller if it has to. Nothing is + // undone when the keyboard goes away again: it stays where it is and as big as it is, so that + // things are not forever moving about. (The page does not shrink for the keyboard, it is covered.) + useEffect(() => { + const viewport = window.visualViewport; + const dialog = dialogRef.current; + if (!viewport || !dialog) return; + let shift = 0; + let fitHeight = Infinity; + + const update = () => { + const keyboardHeight = window.innerHeight - viewport.height - viewport.offsetTop; + if (keyboardHeight < MIN_KEYBOARD_HEIGHT || viewport.scale > 1.01) return; // Not up, or zoomed + + fitHeight = Math.min(fitHeight, viewport.height - 2 * KEYBOARD_GAP); + dialog.style.setProperty("--fit-height", `${fitHeight}px`); + // Where it sits without the shift, measured now that it is the size it is going to be + const nextShift = fitShift( + shift, + dialog.offsetTop, + dialog.offsetHeight, + viewport.offsetTop, + viewport.offsetTop + viewport.height, + KEYBOARD_GAP, + ); + if (nextShift !== shift) { + shift = nextShift; + dialog.style.setProperty("--shift", `${shift}px`); + } + }; + + // The window changes size too, when players come and go, which may be while the keyboard is up + const observer = new ResizeObserver(update); + observer.observe(dialog); + document.addEventListener("focusin", update); + viewport.addEventListener("resize", update); + viewport.addEventListener("scroll", update); + return () => { + observer.disconnect(); + document.removeEventListener("focusin", update); + viewport.removeEventListener("resize", update); + viewport.removeEventListener("scroll", update); + }; + }, []); + + // Escape, and Enter when it is not in a text box or on a button, mean that editing is done + useEffect(() => { + function onKeyDown(event: KeyboardEvent) { + // The color picker has its own idea of what is going on + if (document.querySelector(".color-select-background")) return; + + if (event.key === "Escape") { + onClose(); + return; + } + + if (event.key !== "Enter" || event.repeat) return; // Not the Enter of a key held down + if (event.ctrlKey || event.metaKey || event.altKey || event.shiftKey) return; + + // Where the key was pressed, not where the focus is now: Enter in a name box takes the focus + // out of it, and that Enter has done its job by doing that. On a button, Enter presses it. + const target = event.target; + if (target instanceof Element && target.closest("input, textarea, select, button")) return; + + onClose(); + } + + window.addEventListener("keydown", onKeyDown); + return () => window.removeEventListener("keydown", onKeyDown); + }, [onClose]); + + // The drag effect below calls whichever version of `dragTo` was made by the latest render + const dragToRef = useRef<() => void>(() => {}); + + // While dragging a player: follow the pointer wherever it goes, scroll the list when it nears + // the top or bottom, don't let the user select text, and stop the drag on release + useEffect(() => { + if (dragId === "") return; + + const stopDragging = () => setDragId(""); + const onPointerMove = (e: PointerEvent) => { + pointerY.current = e.clientY; + dragToRef.current(); + }; + // Scrolling moves the list under the pointer, which can mean the player has to change places + const onScroll = () => dragToRef.current(); + const list = listRef.current; + + let frame = 0; + let previousTime: number | undefined; + let carry = 0; // The part of a pixel that was too small to scroll last frame + const autoScroll = (time: number) => { + if (list && previousTime !== undefined) { + const { top, bottom } = list.getBoundingClientRect(); + const speed = autoScrollSpeed(pointerY.current, top, bottom); + carry = speed === 0 ? 0 : carry + (speed * (time - previousTime)) / 1000; + const pixels = Math.trunc(carry); + if (pixels !== 0) { + carry -= pixels; + list.scrollTop += pixels; + } + } + previousTime = time; + frame = requestAnimationFrame(autoScroll); + }; + frame = requestAnimationFrame(autoScroll); + + document.body.style.userSelect = "none"; + window.addEventListener("pointermove", onPointerMove); + window.addEventListener("pointerup", stopDragging); + window.addEventListener("pointercancel", stopDragging); + list?.addEventListener("scroll", onScroll); + + return () => { + cancelAnimationFrame(frame); + document.body.style.userSelect = ""; + window.removeEventListener("pointermove", onPointerMove); + window.removeEventListener("pointerup", stopDragging); + window.removeEventListener("pointercancel", stopDragging); + list?.removeEventListener("scroll", onScroll); + }; + }, [dragId]); + + // FLIP - animate changes in the player order when reordering the player list + useLayoutEffect(() => { + if (dragId === "") return; // No FLIP if we're not actively dragging + + playerRefs.current.forEach((player, id) => { + if (id === dragId) return; // Don't animate the currently dragged item + + const oldRect = playerPositions.current.get(id); + if (!oldRect) return; + + const deltaY = oldRect.top - player.getBoundingClientRect().top; + + if (deltaY !== 0) { + // If there's been a change in position, translate it back to the old position... + player.style.transform = `translateY(${deltaY}px)`; + player.style.transition = "none"; + + // Then remove the translation and let the browser animate + requestAnimationFrame(() => { + player.style.transition = "transform 150ms ease"; + player.style.removeProperty("transform"); + }); + } + }); + }, [game.scorecards, dragId]); + + // Puts the cursor back in the name that was last in, or in the first one if it has gone + function focusANameBox() { + const last = lastNameBox.current; + const box = last?.isConnected + ? last + : dialogRef.current?.querySelector(".player-name-input"); + // Not a press, so not one to select anything + pressedWith.current = "touch"; + box?.focus(); + } + + // On a phone, if the focus ends up on nothing (a name was deleted, say), bring it back to a name, + // so that the keyboard does not go. Not while the color picker is up, which the keyboard would + // cover, nor when the focus has gone to a button. + useEffect(() => { + const dialog = dialogRef.current; + if (!touchDevice || !dialog) return; + const afterFocusMoves = () => + setTimeout(() => { + if (pickerOpen.current) return; + if (document.activeElement === document.body || document.activeElement === dialog) { + focusANameBox(); + } + }, 0); + dialog.addEventListener("focusout", afterFocusMoves); + return () => dialog.removeEventListener("focusout", afterFocusMoves); + }, [touchDevice]); + + useEffect(() => { + pickerOpen.current = selectingColorId !== ""; + }, [selectingColorId]); + + function onColorClick(e: React.MouseEvent, id: string) { + // The keyboard would cover the color picker, so it goes while that is up + if (touchDevice && document.activeElement instanceof HTMLElement) { + document.activeElement.blur(); + } + setSelectingColorId(id); + setColorPickerPosition(e.currentTarget.getBoundingClientRect()); + } + + function deletePlayer(card: Scorecard, index: number) { + updateGame({ type: "delete_player", playerId: card.id }); + showToast({ + message: ( + <> + Deleted{" "} + + + {card.playerName.trim() || "player"} + + + ), + actionLabel: "Undo", + onAction: () => updateGame({ type: "restore_player", card, index }), + }); + // The name that had the focus may have been that one's, and the keyboard goes with it + if (touchDevice) setTimeout(focusANameBox, 0); + } + + function addPlayer() { + const newPlayerId = newId(); + updateGame({ + type: "add_player", + newPlayerId, + newPlayerName: "Player " + (game.scorecards.length + 1), + newPlayerColor: nextPlayerColor(game), + }); + focusPlayerId.current = newPlayerId; // Start editing the new player's name right away + } + + // Measure the position of each player. Used for FLIP animations + function measurePlayerPositions() { + playerRefs.current.forEach((player, id) => { + playerPositions.current.set(id, player.getBoundingClientRect()); + }); + } + + // We need to know what the player spacing is in order to know how far to drag before reordering the list + function measurePlayerSpacing() { + const players = Array.from(playerRefs.current.values()); + if (players.length >= 2) { + const r1 = players[0]!.getBoundingClientRect(); + const r2 = players[1]!.getBoundingClientRect(); + setPlayerSpacing(r2.top - r1.top); + } + } + + function startDragging(e: React.PointerEvent, id: string) { + playerRefs.current.get(id)!.style.removeProperty("transition"); + measurePlayerSpacing(); + measurePlayerPositions(); + // A finger is tied to the handle it touched, and reordering moves that handle in the page, which + // ends the touch. The list stays put, so the drag is held there instead. + listRef.current?.setPointerCapture?.(e.pointerId); + pointerY.current = e.clientY; + dragStartY.current = e.clientY + (listRef.current?.scrollTop ?? 0); + setDragDeltaY(0); + setDragId(id); + } + + // Called whenever the pointer moves or the list scrolls during a drag + function dragTo() { + if (dragId === "") return; + + // Compute how far we've dragged and where the dragged item currently is in the list + const pointerInList = pointerY.current + (listRef.current?.scrollTop ?? 0); + const deltaY = pointerInList - dragStartY.current; + const index = game.scorecards.findIndex((card) => card.id === dragId); + const reorderDistance = (playerSpacing * 3) / 5; + + // Figure out if we need to move the item's position + if (index > 0 && -deltaY > reorderDistance) { + measurePlayerPositions(); + dragStartY.current -= playerSpacing; + updateGame({ type: "move_player", playerId: dragId, direction: "up" }); + } else if (index < game.scorecards.length - 1 && deltaY > reorderDistance) { + measurePlayerPositions(); + dragStartY.current += playerSpacing; + updateGame({ type: "move_player", playerId: dragId, direction: "down" }); + } + + // Need to recompute the delta here because the start Y may have been updated by a reorder + setDragDeltaY(pointerInList - dragStartY.current); + } + + useEffect(() => { + dragToRef.current = dragTo; + }); + + // How far the dragged player at `index` is shifted. The first and last players can only be + // pulled a little past the ends of the list. + function dragOffset(index: number): number { + const overshoot = playerSpacing / 6; + const min = index === 0 ? -overshoot : -Infinity; + const max = index === game.scorecards.length - 1 ? overshoot : Infinity; + return Math.min(Math.max(dragDeltaY, min), max); + } + + return ( +
{ + if (!touchDevice) return; + if (e.target instanceof Element && e.target.closest("input, button")) return; + e.preventDefault(); + }} + > +
+

+ Edit Players +

+
+ {game.scorecards.length === 0 && ( +
+
No players yet
+
+ Press Add player to add one +
+
+ )} + {game.scorecards.map((card, index) => ( + +
{ + if (el) playerRefs.current.set(card.id, el); + else playerRefs.current.delete(card.id); + }} + style={ + card.id === dragId ? { transform: `translateY(${dragOffset(index)}px)` } : {} + } + > +
startDragging(e, card.id)}> + drag_handle +
+
onColorClick(e, card.id)} + /> + { + if (el && focusPlayerId.current === card.id) { + focusPlayerId.current = ""; + // Focusing it selects it, unless it is to be left alone + if (leaveFirstNameAlone.current) pressedWith.current = "touch"; + el.focus(); + pressedWith.current = ""; + if (!leaveFirstNameAlone.current) el.select(); + leaveFirstNameAlone.current = false; + } + }} + value={card.playerName} + // Pressing a name selects all of it, ready to be typed over + onPointerDown={(e) => { + pressedWith.current = e.pointerType; + }} + onFocus={(e) => { + // Used up by this focus. It is not cleared when another name loses the focus, + // as that happens after this press, and before this name gets the focus. + const pointer = pressedWith.current; + pressedWith.current = ""; + lastNameBox.current = e.currentTarget; + // A tap just puts the cursor where it landed + if (pointer === "touch" || pointer === "pen") return; + e.currentTarget.select(); + }} + onMouseDown={(e) => { + keepNameSelected.current = + pressedWith.current === "mouse" && document.activeElement !== e.currentTarget; + }} + onMouseUp={(e) => { + if (!keepNameSelected.current) return; + keepNameSelected.current = false; + e.preventDefault(); + }} + onChange={(e) => + updateGame({ + type: "change_player_name", + playerId: card.id, + newPlayerName: e.target.value, + }) + } + onKeyDown={(e) => { + pressedWith.current = ""; // Whatever moves the focus now is not that press + if (e.key !== "Enter") return; + if (touchDevice) { + // On to the next name, so that the keyboard stays up + e.preventDefault(); + const boxes = Array.from( + dialogRef.current?.querySelectorAll( + ".player-name-input", + ) ?? [], + ); + const next = boxes[boxes.indexOf(e.currentTarget) + 1]; + pressedWith.current = "touch"; + next?.focus(); + return; + } + // Done with this name, so on to the button for adding the next player, which + // Enter will then press. The focus is moved a moment later, as this Enter is + // still on its way, and would otherwise reach the button and press it already. + e.currentTarget.blur(); + setTimeout(() => addButtonRef.current?.focus(), 0); + }} + /> +
deletePlayer(card, index)}> + delete +
+
+ {selectingColorId === card.id && colorPickerPosition && ( + { + setSelectingColorId(""); + if (touchDevice) setTimeout(focusANameBox, 0); + }} + /> + )} + + ))} +
+
+ + +
+
+
+ ); +} diff --git a/web/src/components/game-play-page/enter-scores-component/EnterScoresComponent.tsx b/web/src/components/game-play-page/enter-scores-component/EnterScoresComponent.tsx index 7fff41e..15a392d 100644 --- a/web/src/components/game-play-page/enter-scores-component/EnterScoresComponent.tsx +++ b/web/src/components/game-play-page/enter-scores-component/EnterScoresComponent.tsx @@ -31,6 +31,16 @@ const keys = [ }, ]; +/** Which key of the keypad a key of the keyboard is pressing, if any */ +function keypadKeyFor(key: string): string | null { + if (key.length === 1 && key >= "0" && key <= "9") return key; + if (key === ".") return "."; + if (key === "-" || key === "+") return "+/-"; + if (key === "Backspace" || key === "Delete") return "Backspace"; + if (key === "Enter") return "Enter"; + return null; +} + /** How long a key stays pressed in at least, as a quick tap is over before it could be seen */ const MIN_PRESS_MS = 140; @@ -64,19 +74,22 @@ export function EnterScoresComponent({ const pressedAt = useRef(0); const releaseTimer = useRef>(undefined); - const pressDown = (key: string, time: number) => { + // The key of the keypad that the key of the keyboard being held down is pressing, if there is one + const keyboardPressing = useRef(null); + + const pressDown = useCallback((key: string, time: number) => { clearTimeout(releaseTimer.current); pressedAt.current = time; setPressedKey(key); - }; + }, []); // Lets go, but not before the press has been there long enough to be seen - const release = (time: number) => { + const release = useCallback((time: number) => { clearTimeout(releaseTimer.current); const remaining = MIN_PRESS_MS - (time - pressedAt.current); if (remaining <= 0) setPressedKey(null); else releaseTimer.current = setTimeout(() => setPressedKey(null), remaining); - }; + }, []); useEffect(() => () => clearTimeout(releaseTimer.current), []); @@ -119,16 +132,34 @@ export function EnterScoresComponent({ const focused = document.activeElement; if ((e.key === "Enter" || e.key === " ") && focused instanceof HTMLButtonElement) return; - // While the players are being edited, Enter finishes that, rather than entering a score - if (editing && e.key === "Enter") return; + // While the players are being edited in the window over the page, the keys are for that + if (editing) return; - if (!editing) (focused as HTMLElement | null)?.blur(); + (focused as HTMLElement | null)?.blur(); + // The key of the keypad looks pressed, as it would for a click + const pad = keypadKeyFor(e.key); + if (pad) { + keyboardPressing.current = pad; + pressDown(pad, e.timeStamp); + } pressKey(e.key); } + function handleKeyUp(e: KeyboardEvent) { + const pad = keypadKeyFor(e.key); + // Only if it is the key that is the latest to have been pressed that is let go of + if (!pad || pad !== keyboardPressing.current) return; + keyboardPressing.current = null; + release(e.timeStamp); + } + window.addEventListener("keydown", handleKeyDown); - return () => window.removeEventListener("keydown", handleKeyDown); - }, [pressKey, editing]); + window.addEventListener("keyup", handleKeyUp); + return () => { + window.removeEventListener("keydown", handleKeyDown); + window.removeEventListener("keyup", handleKeyUp); + }; + }, [pressKey, pressDown, release, editing]); return (
diff --git a/web/src/components/game-play-page/player-list-component/PlayerListComponent.scss b/web/src/components/game-play-page/player-list-component/PlayerListComponent.scss index bec6e5f..b7b24ed 100644 --- a/web/src/components/game-play-page/player-list-component/PlayerListComponent.scss +++ b/web/src/components/game-play-page/player-list-component/PlayerListComponent.scss @@ -1,4 +1,3 @@ -@use "sass:color"; @use "../../../Colors.scss" as *; @use "../../../Breakpoints.scss" as *; @@ -12,19 +11,61 @@ $drag-room: 10px; $corner-room: 14px; // How far the list fades out at an edge that has more of it beyond, instead of cutting off $fade-size: 36px; -$flash-duration: 800ms; -$done-color: color.mix($light-elements, $gray-3, 75%); // The same as the Enter key -$flash-color: rgba($light-elements, 0.35); +$bounce-duration: 400ms; -@keyframes player-flash-a { +// A score that has just been updated hops up in size and settles back. There are two copies of it so +// that a second update straight after the first can start it over. +// What changes with the round slides in from the side that the new round is on +@keyframes slide-from-next { from { - background-color: $flash-color; + transform: translateX(28px); + opacity: 0; } } -@keyframes player-flash-b { +@keyframes slide-from-prev { from { - background-color: $flash-color; + transform: translateX(-28px); + opacity: 0; + } +} + +.slide-from-next { + animation: slide-from-next 200ms ease-out; +} + +.slide-from-prev { + animation: slide-from-prev 200ms ease-out; +} + +@media (prefers-reduced-motion: reduce) { + .slide-from-next, + .slide-from-prev { + animation: none; + } +} + +@keyframes score-bounce-a { + 12.5% { + transform: scale(1.35); + } + 55% { + transform: scale(0.92); + } + 75% { + transform: scale(1.08); + } +} + +@keyframes score-bounce-b { + 12.5% { + transform: scale(1.35); + } + 55% { + transform: scale(0.92); + } + 75% { + transform: scale(1.08); } } @@ -101,11 +142,18 @@ $flash-color: rgba($light-elements, 0.35); // the heading changes, instead of following its width min-width: 136px; padding-bottom: 3px; + overflow: hidden; // So that the heading slides in from the edge of this, not over the arrows color: $light-elements; font-size: 18pt; font-weight: bold; text-align: center; white-space: nowrap; + + // A plain inline element cannot be moved by a transform, which is all that would be left of the + // slide, with only the fading in of it + > span { + display: inline-block; + } } // Stacked, the list is a panel of its own with space on both sides @@ -193,24 +241,12 @@ $flash-color: rgba($light-elements, 0.35); mask-image: $fade; } - // ...except while the players are being edited, when it is only as tall as they need, so that the - // add player button comes right after the last one. Once the players fill the room there is, it - // stops growing, and the buttons stay in view below it. - &.editing { - flex: 0 1 auto; - - // With no room to spare to centre it in, the message would sit right on top of the buttons - .player-list-empty { - margin: 0 0 16px; - } - } - .player { position: relative; isolation: isolate; // So the hit area below can sit behind this player's own content flex: none; // Rows keep their height instead of being squashed to fit width: 100%; - height: $row-height; // The same in edit mode, where the name is in a box + height: $row-height; display: flex; align-items: center; gap: 10px; @@ -230,14 +266,7 @@ $flash-color: rgba($light-elements, 0.35); inset: (-$player-gap * 0.5) 0; } - &.dragging { - z-index: 1; - background-color: $gray-2; - box-shadow: 0 0 6px 0 black; - transition: none; - } - - &:not(.editing):not(.selected):not(.pinned):hover { + &:not(.selected):not(.pinned):hover { background-color: $gray-2; transition: background-color 40ms ease; } @@ -248,49 +277,10 @@ $flash-color: rgba($light-elements, 0.35); background-color: $gray-4; } - // Flashes when the player's score has just been updated. The animation only says where to - // start, so it fades back to whatever the row looks like otherwise. There are two copies of - // it so that a second update straight after the first can start it over. - &.flash-a { - animation: player-flash-a $flash-duration ease-out; - } - - &.flash-b { - animation: player-flash-b $flash-duration ease-out; - } - - @media (prefers-reduced-motion: reduce) { - &.flash-a, - &.flash-b { - animation: none; - } - } - .spacer-left { width: 10px; } - .drag-handle { - color: $light-elements; - cursor: grab; - touch-action: none; // Or a finger dragging it would scroll the list instead, and cancel the drag - overflow: hidden; - align-self: stretch; - width: $row-height; - display: flex; - align-items: center; - justify-content: center; - transition: width 60ms ease; - - &.hidden { - width: 0; - } - } - - &.dragging .drag-handle { - cursor: grabbing; - } - .player-color { align-self: stretch; width: $row-height; @@ -308,53 +298,26 @@ $flash-color: rgba($light-elements, 0.35); white-space: nowrap; } - .player-name-input { - background-color: $gray-3; - flex: 1; - width: 0; // Size comes from flex-grow only, not the input's intrinsic width - min-width: 0; - height: 32px; - padding: 0 8px; - border: 1px solid $gray-5; - border-radius: 8px; - color: $light-elements; - font-family: inherit; - font-size: 18pt; - font-weight: bold; - - &:focus { - outline: none; - border-color: $light-elements; - } - } - .score { color: $light-elements; font-size: 18pt; font-weight: bold; - overflow: hidden; display: flex; align-items: center; - transition: width 60ms ease; - &.hidden { - width: 0; + &.flash-a { + animation: score-bounce-a $bounce-duration ease-out; } - } - .delete-button { - color: $light-elements; - cursor: pointer; - overflow: hidden; - align-self: stretch; - width: $row-height; - display: flex; - align-items: center; - justify-content: center; - transition: width 60ms ease; + &.flash-b { + animation: score-bounce-b $bounce-duration ease-out; + } - &.hidden { - width: 0; + @media (prefers-reduced-motion: reduce) { + &.flash-a, + &.flash-b { + animation: none; + } } } @@ -376,84 +339,3 @@ $flash-color: rgba($light-elements, 0.35); } } } - -// The buttons below the players: for editing them, and for adding one (and finishing) while they are -// being edited. It follows the last player, or stays in view below the scrolling list if there are -// many. -.list-footer { - flex: none; - // The room below the list, and the room the list leaves for the panel's corners, make up the gap - margin: (12px - $drag-room - $corner-room) 0 10px; // The bottom lines up with the button that expands the list - display: flex; - justify-content: center; - gap: 12px; - - button { - @include secondary-button; - min-height: 44px; - padding: 0 20px 0 14px; - display: flex; - align-items: center; - gap: 8px; - font-size: 15px; - font-weight: 600; - - .material-symbols-outlined { - font-size: 22px; - } - } - - // Not wanted often, so it is quiet until it is pointed at - .edit-players-button { - background-color: transparent; - border-color: $gray-3; - color: rgba($light-elements, 0.45); - - @media (hover: hover) { - &:hover:not(:active) { - background-color: $gray-2; - border-color: $gray-5; - color: $light-elements; - } - } - } - - // An empty place for another player: a dashed outline that fills in when it is pointed at - .add-player-button { - background-color: transparent; - border: 2px dashed $gray-5; - color: rgba($light-elements, 0.75); - - @media (hover: hover) { - &:hover { - border-color: $light-elements; - color: $light-elements; - } - } - - &:active { - border-color: $light-elements; - color: $light-elements; - } - } - - // The way out of editing, so it is as prominent as the Enter key of the keypad - .done-button { - background-color: $done-color; - border-color: $done-color; - color: $background; - - // The same selectors as the shared button's hover and press, to win over its backgrounds - @media (hover: hover) { - &:hover:not(:disabled) { - background-color: $done-color; - filter: brightness(0.94); - } - } - - &:active:not(:disabled) { - background-color: $done-color; - filter: brightness(0.85); - } - } -} diff --git a/web/src/components/game-play-page/player-list-component/PlayerListComponent.tsx b/web/src/components/game-play-page/player-list-component/PlayerListComponent.tsx index bde546b..3c9954b 100644 --- a/web/src/components/game-play-page/player-list-component/PlayerListComponent.tsx +++ b/web/src/components/game-play-page/player-list-component/PlayerListComponent.tsx @@ -1,13 +1,8 @@ import "./PlayerListComponent.scss"; import clsx from "clsx"; -import React, { useLayoutEffect, useState, useRef, useEffect } from "react"; +import { useRef, useEffect, useState } from "react"; import { useGame } from "@/GameContext"; -import { useToast } from "@/ToastContext"; -import { nextPlayerColor, type Scorecard } from "@/Game"; import { totalScore } from "@/utils/Scores"; -import { autoScrollSpeed } from "@/utils/autoScroll"; -import { newId } from "@/utils/newId"; -import { SelectColorComponent } from "./SelectColorComponent/SelectColorComponent"; /** The round passed in when the player list should show total scores instead of a round */ const TOTAL_SCORES = -1; @@ -17,13 +12,13 @@ function hiddenFromEveryone(hidden: boolean) { return hidden ? { tabIndex: -1, "aria-hidden": true } : {}; } -function roundLabel(round: number, editing: boolean): string { - if (editing) return "Edit Players"; +function roundLabel(round: number): string { if (round === TOTAL_SCORES) return "Total Scores"; if (round === 0) return "Initial Score"; return `Round ${round}`; } +/** The players and their scores, for looking at and for picking who the next score is for */ export function PlayerListComponent({ round, selectedPlayerId, @@ -33,9 +28,6 @@ export function PlayerListComponent({ onHighlightPlayer, pinnedPlayerId, flashCounts, - editing, - onStartEditing, - onFinishEditing, }: { round: number; selectedPlayerId: string; @@ -47,41 +39,50 @@ export function PlayerListComponent({ /** The player whose line has been picked out on the plot by pressing them, if any */ pinnedPlayerId: string; /** - * How many times each player's row has been told to flash. A row flashes when its count goes + * How many times each player's score has been told to bounce. A score bounces when its count goes * up, however many times that has already happened. */ flashCounts: Record; - /** Whether the players are being edited: renamed, reordered, recolored, added and deleted */ - editing: boolean; - onStartEditing: () => void; - onFinishEditing: () => void; }) { - const { game, updateGame } = useGame(); - const { showToast, dismissAll } = useToast(); - // The player whose name field should be focused as soon as it appears (a just-added player) - const focusPlayerId = useRef(""); - const addButtonRef = useRef(null); - const [selectingColorId, setSelectingColorId] = useState(""); - const [colorPickerPosition, setColorPickerPosition] = useState(null); - const [dragId, setDragId] = useState(""); + const { game } = useGame(); const listRef = useRef(null); - // While dragging, positions are measured down the whole list, scrolled out of view or not: the - // pointer's Y plus how far the list has scrolled. Then scrolling the list under a pointer that's - // standing still moves the dragged player along with it. - const dragStartY = useRef(0); - const pointerY = useRef(0); // The latest position of the pointer on the screen, while dragging - const [dragDeltaY, setDragDeltaY] = useState(0); - const [playerSpacing, setPlayerSpacing] = useState(0); const playerRefs = useRef>(new Map()); - const playerPositions = useRef>(new Map()); const showingRound = round !== TOTAL_SCORES; - // Keep the selected player in view as the keypad moves through the list + // Going from one round to another, the heading and the scores slide in from the side that the new + // round is on (the next round from the right, the one before from the left). Changing between a + // round and the total scores is not that, so they are left alone. It is worked out as the round + // changes (and not in an effect after it), so that they are there with the new round, as it appears. + const [shownRound, setShownRound] = useState(round); + const [roundChange, setRoundChange] = useState({ direction: "next", count: 0 }); + if (shownRound !== round) { + setShownRound(round); + if (round !== TOTAL_SCORES && shownRound !== TOTAL_SCORES) { + setRoundChange((change) => ({ + direction: round > shownRound ? "next" : "prev", + count: change.count + 1, + })); + } + } + // Each change is a new element, which is what starts its animation + const slideClass = roundChange.count > 0 ? `slide-from-${roundChange.direction}` : undefined; + + // Keep the selected player in the middle of the list as the keypad moves through it, gliding + // there from the one before. Where there is no one before (the list has only just come up), or + // for somebody who would rather not have things move about, it is just there. + const previousSelectedId = useRef(undefined); useEffect(() => { - if (editing || !showingRound) return; - playerRefs.current.get(selectedPlayerId)?.scrollIntoView?.({ block: "nearest" }); - }, [selectedPlayerId, editing, showingRound]); + if (!showingRound) return; + const moved = + previousSelectedId.current !== undefined && previousSelectedId.current !== selectedPlayerId; + previousSelectedId.current = selectedPlayerId; + const reducedMotion = window.matchMedia?.("(prefers-reduced-motion: reduce)").matches; + playerRefs.current.get(selectedPlayerId)?.scrollIntoView?.({ + block: "center", + behavior: moved && !reducedMotion ? "smooth" : "instant", + }); + }, [selectedPlayerId, showingRound]); // Let the stylesheet know whether there is more of the list above or below what can be seen, so // that the list can fade out at an edge that has more beyond it, rather than being cut off. This @@ -100,7 +101,7 @@ export function PlayerListComponent({ update(); list.addEventListener("scroll", update, { passive: true }); - // The size changes with the window, and when the add player button comes and goes + // The size changes with the window const observer = new ResizeObserver(update); observer.observe(list); @@ -110,208 +111,31 @@ export function PlayerListComponent({ }; }, [game.scorecards.length]); // And when there are more or fewer players to scroll through - // The drag effect below calls whichever version of `dragTo` was made by the latest render - const dragToRef = useRef<() => void>(() => {}); - - // While dragging a player: follow the pointer wherever it goes, scroll the list when it nears - // the top or bottom, don't let the user select text, and stop the drag on release - useEffect(() => { - if (dragId === "") return; - - const stopDragging = () => setDragId(""); - const onPointerMove = (e: PointerEvent) => { - pointerY.current = e.clientY; - dragToRef.current(); - }; - // Scrolling moves the list under the pointer, which can mean the player has to change places - const onScroll = () => dragToRef.current(); - const list = listRef.current; - - let frame = 0; - let previousTime: number | undefined; - let carry = 0; // The part of a pixel that was too small to scroll last frame - const autoScroll = (time: number) => { - if (list && previousTime !== undefined) { - const { top, bottom } = list.getBoundingClientRect(); - const speed = autoScrollSpeed(pointerY.current, top, bottom); - carry = speed === 0 ? 0 : carry + (speed * (time - previousTime)) / 1000; - const pixels = Math.trunc(carry); - if (pixels !== 0) { - carry -= pixels; - list.scrollTop += pixels; - } - } - previousTime = time; - frame = requestAnimationFrame(autoScroll); - }; - frame = requestAnimationFrame(autoScroll); - - document.body.style.userSelect = "none"; - window.addEventListener("pointermove", onPointerMove); - window.addEventListener("pointerup", stopDragging); - window.addEventListener("pointercancel", stopDragging); - list?.addEventListener("scroll", onScroll); - - return () => { - cancelAnimationFrame(frame); - document.body.style.userSelect = ""; - window.removeEventListener("pointermove", onPointerMove); - window.removeEventListener("pointerup", stopDragging); - window.removeEventListener("pointercancel", stopDragging); - list?.removeEventListener("scroll", onScroll); - }; - }, [dragId]); - - // FLIP - animate changes in the player order when reordering the player list - useLayoutEffect(() => { - if (dragId === "") return; // No FLIP if we're not actively dragging - - playerRefs.current.forEach((player, id) => { - if (id === dragId) return; // Don't animate the currently dragged item - - const oldRect = playerPositions.current.get(id); - if (!oldRect) return; - - const deltaY = oldRect.top - player.getBoundingClientRect().top; - - if (deltaY !== 0) { - // If there's been a change in position, translate it back to the old position... - player.style.transform = `translateY(${deltaY}px)`; - player.style.transition = "none"; - - // Then remove the translation and let the browser animate - requestAnimationFrame(() => { - player.style.transition = "transform 150ms ease"; - player.style.removeProperty("transform"); - }); - } - }); - }, [game.scorecards, dragId]); - - function onColorClick(e: React.MouseEvent, id: string) { - if (editing) { - setSelectingColorId(id); - setColorPickerPosition(e.currentTarget.getBoundingClientRect()); - } - } - - function deletePlayer(card: Scorecard, index: number) { - updateGame({ type: "delete_player", playerId: card.id }); - showToast({ - message: ( - <> - Deleted{" "} - - - {card.playerName.trim() || "player"} - - - ), - actionLabel: "Undo", - onAction: () => updateGame({ type: "restore_player", card, index }), - }); - } - - function addPlayer() { - const newPlayerId = newId(); - updateGame({ - type: "add_player", - newPlayerId, - newPlayerName: "Player " + (game.scorecards.length + 1), - newPlayerColor: nextPlayerColor(game), - }); - focusPlayerId.current = newPlayerId; // Start editing the new player's name right away - } - - // Measure the position of each player. Used for FLIP animations - function measurePlayerPositions() { - playerRefs.current.forEach((player, id) => { - playerPositions.current.set(id, player.getBoundingClientRect()); - }); - } - - // We need to know what the player spacing is in order to know how far to drag before reordering the list - function measurePlayerSpacing() { - const players = Array.from(playerRefs.current.values()); - if (players.length >= 2) { - const r1 = players[0]!.getBoundingClientRect(); - const r2 = players[1]!.getBoundingClientRect(); - setPlayerSpacing(r2.top - r1.top); - } - } - - function startDragging(e: React.PointerEvent, id: string) { - playerRefs.current.get(id)!.style.removeProperty("transition"); - measurePlayerSpacing(); - measurePlayerPositions(); - // A finger is tied to the handle it touched, and reordering moves that handle in the page, which - // ends the touch. The list stays put, so the drag is held there instead. - listRef.current?.setPointerCapture?.(e.pointerId); - pointerY.current = e.clientY; - dragStartY.current = e.clientY + (listRef.current?.scrollTop ?? 0); - setDragDeltaY(0); - setDragId(id); - } - - // Called whenever the pointer moves or the list scrolls during a drag - function dragTo() { - if (dragId === "") return; - - // Compute how far we've dragged and where the dragged item currently is in the list - const pointerInList = pointerY.current + (listRef.current?.scrollTop ?? 0); - const deltaY = pointerInList - dragStartY.current; - const index = game.scorecards.findIndex((card) => card.id === dragId); - const reorderDistance = (playerSpacing * 3) / 5; - - // Figure out if we need to move the item's position - if (index > 0 && -deltaY > reorderDistance) { - measurePlayerPositions(); - dragStartY.current -= playerSpacing; - updateGame({ type: "move_player", playerId: dragId, direction: "up" }); - } else if (index < game.scorecards.length - 1 && deltaY > reorderDistance) { - measurePlayerPositions(); - dragStartY.current += playerSpacing; - updateGame({ type: "move_player", playerId: dragId, direction: "down" }); - } - - // Need to recompute the delta here because the start Y may have been updated by a reorder - setDragDeltaY(pointerInList - dragStartY.current); - } - - useEffect(() => { - dragToRef.current = dragTo; - }); - - // How far the dragged player at `index` is shifted. The first and last players can only be - // pulled a little past the ends of the list. - function dragOffset(index: number): number { - const overshoot = playerSpacing / 6; - const min = index === 0 ? -overshoot : -Infinity; - const max = index === game.scorecards.length - 1 ? overshoot : Infinity; - return Math.min(Math.max(dragDeltaY, min), max); - } - return ( <>
-
{roundLabel(round, editing)}
+
+ + {roundLabel(round)} + +
-
+
{game.scorecards.length === 0 && (
No players yet
- Press{" "} - - {editing ? "Add player" : "Edit players"} - {" "} - {editing ? "to add one" : "to add some"} + Press Edit players to add some
)} - {game.scorecards.map((card, index) => ( - + {game.scorecards.map((card) => ( +
onSelectPlayer(card.id)} + // Only for a real mouse. A touchscreen pretends to hover over what was tapped, and + // leaves it that way, which would make it impossible to let go of a pinned player. + onPointerEnter={(e) => e.pointerType === "mouse" && onHighlightPlayer(card.id)} + onPointerLeave={(e) => e.pointerType === "mouse" && onHighlightPlayer("")} + ref={(el) => { + if (el) playerRefs.current.set(card.id, el); + else playerRefs.current.delete(card.id); + }} + > +
+
+
{card.playerName}
0 && (flashCounts[card.id] ?? 0) % 2 === 0, })} - onClick={() => onSelectPlayer(card.id)} - // Only for a real mouse. A touchscreen pretends to hover over what was tapped, and - // leaves it that way, which would make it impossible to let go of a pinned player. - onPointerEnter={(e) => e.pointerType === "mouse" && onHighlightPlayer(card.id)} - onPointerLeave={(e) => e.pointerType === "mouse" && onHighlightPlayer("")} - ref={(el) => { - if (el) playerRefs.current.set(card.id, el); - else playerRefs.current.delete(card.id); - }} - style={card.id === dragId ? { transform: `translateY(${dragOffset(index)}px)` } : {}} > -
-
startDragging(e, card.id)} - > - drag_handle -
-
onColorClick(e, card.id)} - /> - {editing ? ( - { - if (el && focusPlayerId.current === card.id) { - focusPlayerId.current = ""; - el.focus(); - el.select(); - } - }} - value={card.playerName} - onChange={(e) => - updateGame({ - type: "change_player_name", - playerId: card.id, - newPlayerName: e.target.value, - }) - } - onKeyDown={(e) => { - if (e.key !== "Enter") return; - // Done with this name, so on to the button for adding the next player, which - // Enter will then press. The focus is moved a moment later, as this Enter is - // still on its way, and would otherwise reach the button and press it already. - e.currentTarget.blur(); - setTimeout(() => addButtonRef.current?.focus(), 0); - }} - /> - ) : ( -
{card.playerName}
- )} -
+ {showingRound ? (card.scores[round] ?? 0) : totalScore(card)} -
-
deletePlayer(card, index)} - > - delete -
-
+
- {selectingColorId === card.id && colorPickerPosition && ( - setSelectingColorId("")} - /> - )} - +
+
))}
-
- {editing ? ( - <> - - - - ) : ( - - )} -
); } diff --git a/web/src/components/game-play-page/player-list-component/SelectColorComponent/SelectColorComponent.scss b/web/src/components/game-play-page/player-list-component/SelectColorComponent/SelectColorComponent.scss index aaa5f6c..4d14207 100644 --- a/web/src/components/game-play-page/player-list-component/SelectColorComponent/SelectColorComponent.scss +++ b/web/src/components/game-play-page/player-list-component/SelectColorComponent/SelectColorComponent.scss @@ -40,18 +40,19 @@ $cream: #f0e0b8; border-bottom-left-radius: 4px; } +// The same panel wherever it is: two rows of colors, then the custom color below them. Beside the +// color it is for on a big screen, and in the middle of the screen on a phone (see below). .color-select-content { - --card-size: 60px; - --slider-width: 200px; + --card-size: 44px; --thumb-size: 18px; - width: fit-content; + box-sizing: border-box; + width: 340px; background-color: $gray-1; border: 1px solid $gray-4; border-radius: 16px; - padding: 20px 28px; + padding: 20px; display: flex; - // align-items: center; - gap: 12px; + flex-direction: column; .color-card { height: var(--card-size); @@ -76,31 +77,40 @@ $cream: #f0e0b8; } .default-colors-section { - display: flex; - gap: 20px; + display: grid; + grid-template-columns: repeat(4, var(--card-size)); + justify-content: space-between; + row-gap: 16px; } .color-section-divider { - margin: -8px 10px; - width: 3px; + height: 3px; + margin: 20px -4px; background-color: $gray-4; } .custom-color-section { display: flex; - gap: 10px; + align-items: center; + gap: 16px; + + .color-card { + flex: none; + } .color-sliders { + flex: 1; display: flex; flex-direction: column; justify-content: space-between; + gap: 18px; .color-slider { appearance: none; - width: var(--slider-width); - height: 12px; + width: 100%; + height: 14px; margin: 0; - border-radius: 6px; + border-radius: 7px; box-shadow: inset 0 0 0 1px #ffffff1a; cursor: pointer; @@ -156,6 +166,11 @@ $cream: #f0e0b8; } } } + + // Only on a phone, see below + .color-done-button { + display: none; + } } // On a phone the picker is a panel in the middle of the screen, as there is no room beside the color @@ -166,51 +181,47 @@ $cream: #f0e0b8; // The position is set in the style attribute, for the layout beside the color .color-select-content { - --card-size: 44px; --thumb-size: 28px; position: fixed !important; left: 50% !important; top: 50% !important; transform: translate(-50%, -50%); - box-sizing: border-box; width: min(340px, calc(100vw - 32px)); max-height: calc(100dvh - 24px); overflow-y: auto; - flex-direction: column; - gap: 0; - padding: 20px; - - .default-colors-section { - display: grid; - grid-template-columns: repeat(4, var(--card-size)); - justify-content: space-between; - row-gap: 16px; - } - - .color-section-divider { - width: auto; - height: 3px; - margin: 20px -4px; - } - .custom-color-section { + // Quiet, like the other secondary buttons, and only as wide as it needs to be + .color-done-button { + min-height: 44px; + margin-top: 28px; + padding: 0 20px 0 14px; + display: flex; + flex: none; + align-self: center; align-items: center; - gap: 16px; - - .color-card { - flex: none; + gap: 8px; + background-color: $gray-2; + border: 1px solid $gray-4; + border-radius: 12px; + color: $light-elements; + cursor: pointer; + font-family: inherit; + font-size: 15px; + font-weight: 600; + touch-action: manipulation; + -webkit-tap-highlight-color: transparent; + + &:active { + background-color: $gray-4; } - .color-sliders { - flex: 1; - gap: 18px; - - .color-slider { - width: 100%; - height: 14px; - border-radius: 7px; - } + .material-symbols-outlined { + font-size: 22px; } } + + .custom-color-section .color-sliders .color-slider { + height: 14px; + } } } diff --git a/web/src/components/game-play-page/player-list-component/SelectColorComponent/SelectColorComponent.tsx b/web/src/components/game-play-page/player-list-component/SelectColorComponent/SelectColorComponent.tsx index c94a0d5..94101d4 100644 --- a/web/src/components/game-play-page/player-list-component/SelectColorComponent/SelectColorComponent.tsx +++ b/web/src/components/game-play-page/player-list-component/SelectColorComponent/SelectColorComponent.tsx @@ -22,7 +22,7 @@ function reachable(color: Hsl): Hsl { } // The picker's height, which it has to leave room for below itself, and how far to stay from the edge -const pickerHeight = 102; +const pickerHeight = 270; const screenMargin = 12; export function SelectColorComponent({ @@ -41,6 +41,8 @@ export function SelectColorComponent({ const [closing, setClosing] = useState(false); const [ring, setRing] = useState<{ left: number; top: number } | null>(null); const contentRef = useRef(null); + // How tall the picker really is, once it is there, for centering it on the color + const [height, setHeight] = useState(pickerHeight); const customHex = hslToHex(customColor); const isCustom = !defaultColors.includes(currentColor); @@ -58,6 +60,11 @@ export function SelectColorComponent({ }); }, [currentColor]); + useLayoutEffect(() => { + const measured = contentRef.current?.offsetHeight; + if (measured) setHeight(measured); + }, []); + function setPlayerColor(color: string) { updateGame({ type: "change_player_color", playerId, newColor: color }); } @@ -81,8 +88,8 @@ export function SelectColorComponent({ className="color-select-content-nub" style={{ position: "absolute", - left: position.x + 40, - top: position.y + 8, + left: position.x + 46, + top: position.y + position.height / 2 - 8, // Level with the middle of the color }} />
e.stopPropagation()} style={{ position: "absolute", - left: position.x + 48, - // Next to the color, but not so low that the bottom of the picker is off the screen + left: position.x + 54, + // Level with the middle of the color, but not so high or so low that the picker is off the screen top: Math.max( screenMargin, - Math.min(position.y - 35, window.innerHeight - pickerHeight - screenMargin), + Math.min( + position.y + position.height / 2 - height / 2, + window.innerHeight - height - screenMargin, + ), ), }} > @@ -146,6 +156,17 @@ export function SelectColorComponent({ ))}
+ {/* For phones, where there is no way to tell that a press outside the panel closes it */} +
, document.body, diff --git a/web/src/components/game-play-page/score-table-component/ScoreTableComponent.test.tsx b/web/src/components/game-play-page/score-table-component/ScoreTableComponent.test.tsx index 60b9c51..43b58f8 100644 --- a/web/src/components/game-play-page/score-table-component/ScoreTableComponent.test.tsx +++ b/web/src/components/game-play-page/score-table-component/ScoreTableComponent.test.tsx @@ -44,7 +44,7 @@ describe("editing a score in the table", () => { it("says that scores can be edited", () => { renderTable(); - expect(screen.getByText("Tap a score to edit it")).toBeTruthy(); + expect(screen.getByText("Click a score to edit it")).toBeTruthy(); }); it("turns the score into a text box, with the number selected and ready to be typed over", async () => { @@ -101,7 +101,7 @@ describe("editing a score in the table", () => { await user.click(scoreButton("Bo", "round 2")); await user.keyboard("7"); - await user.click(screen.getByText("Tap a score to edit it")); + await user.click(screen.getByText("Click a score to edit it")); expect(updateGame).toHaveBeenCalledExactlyOnceWith({ type: "add_score", @@ -259,7 +259,7 @@ describe("editing a score in the table", () => { await user.click(scoreButton("Ada", "round 1")); await user.keyboard("9"); - await user.click(screen.getByText("Tap a score to edit it")); + await user.click(screen.getByText("Click a score to edit it")); expect(document.activeElement).not.toBe(scoreButton("Ada", "round 1")); }); diff --git a/web/src/components/game-play-page/score-table-component/ScoreTableComponent.tsx b/web/src/components/game-play-page/score-table-component/ScoreTableComponent.tsx index c96296b..967fa8b 100644 --- a/web/src/components/game-play-page/score-table-component/ScoreTableComponent.tsx +++ b/web/src/components/game-play-page/score-table-component/ScoreTableComponent.tsx @@ -143,7 +143,7 @@ export function ScoreTableComponent({
-
Tap a score to edit it
+
Click a score to edit it
); } diff --git a/web/src/components/title-page/TitlePage.scss b/web/src/components/title-page/TitlePage.scss index 74efe10..f700bf8 100644 --- a/web/src/components/title-page/TitlePage.scss +++ b/web/src/components/title-page/TitlePage.scss @@ -188,15 +188,6 @@ $accent: color.mix($light-elements, $gray-3, 75%); // The same as the Enter key text-transform: uppercase; } - .continue-game-name { - max-width: 100%; - overflow: hidden; - font-size: 17pt; - font-weight: 700; - text-overflow: ellipsis; - white-space: nowrap; - } - .continue-game-details { font-size: 11pt; font-weight: 500; @@ -214,8 +205,8 @@ $accent: color.mix($light-elements, $gray-3, 75%); // The same as the Enter key // away off the left of the screen, or in from it. The card is only on one of the two pages, so it // only ever has one of these. // Going to the game is quicker than coming back to the title, as it is the one that is in the way -$to-title-time: 450ms; -$to-game-time: 250ms; +$to-title-time: 350ms; +$to-game-time: 180ms; // The lines go sooner than the game page arrives, so that they are not seen through it $lines-out-time: 120ms; diff --git a/web/src/components/title-page/TitlePage.tsx b/web/src/components/title-page/TitlePage.tsx index a619308..5cd5e4a 100644 --- a/web/src/components/title-page/TitlePage.tsx +++ b/web/src/components/title-page/TitlePage.tsx @@ -2,9 +2,7 @@ import "./TitlePage.scss"; import { useRef, useState } from "react"; import { useNavigate } from "react-router-dom"; import { defaultColors, supportOptions } from "@/config"; -import { isUntouched } from "@/Game"; import { useGame } from "@/GameContext"; -import { useToast } from "@/ToastContext"; import { lastRound } from "@/utils/Scores"; import { runWithTransition, usePageAppeared } from "@/viewTransition"; import { ScoreLinesBackdrop } from "./ScoreLinesBackdrop"; @@ -18,7 +16,6 @@ function plural(count: number, noun: string): string { export function TitlePage() { const navigate = useNavigate(); const { game, updateGame, hasGame } = useGame(); - const { showToast } = useToast(); usePageAppeared(); const [supportOpen, setSupportOpen] = useState(false); const supportLinkRef = useRef(null); @@ -31,18 +28,8 @@ export function TitlePage() { } function startNewGame() { - const previous = game; - const losingSomething = hasGame && !isUntouched(previous); - runWithTransition(() => { updateGame({ type: "new_game" }); - if (losingSomething) { - showToast({ - message: "Started a new game", - actionLabel: "Undo", - onAction: () => updateGame({ type: "load_game", game: previous }), - }); - } navigate("/play", { state: { newGame: true } }); }, "to-game"); } @@ -73,7 +60,6 @@ export function TitlePage() { > Continue Game - {game.name} {plural(game.scorecards.length, "player")} · {plural(lastRound(game), "round")} diff --git a/web/src/utils/fitInView.test.ts b/web/src/utils/fitInView.test.ts new file mode 100644 index 0000000..e8824ab --- /dev/null +++ b/web/src/utils/fitInView.test.ts @@ -0,0 +1,31 @@ +import { describe, expect, it } from "vitest"; +import { fitShift } from "./fitInView"; + +// A screen 800 high, with the keyboard leaving the top 500 of it +describe("fitShift", () => { + it("leaves a box that is in view where it is", () => { + expect(fitShift(0, 100, 300, 0, 500, 12)).toBe(0); + }); + + it("moves a box up just far enough to clear the keyboard", () => { + // Its bottom is at 600, and has to be at 488 + expect(fitShift(0, 300, 300, 0, 500, 12)).toBe(-112); + }); + + it("keeps a box that was moved up where it is, when it still fits", () => { + expect(fitShift(-112, 300, 300, 0, 500, 12)).toBe(-112); + }); + + it("moves it up further if the keyboard needs more of the room", () => { + expect(fitShift(-112, 300, 300, 0, 400, 12)).toBe(-212); + }); + + it("does not take a box off the top of what is visible", () => { + // Too tall to fit: it is stopped at the top margin rather than pushed up out of sight + expect(fitShift(-500, 300, 300, 0, 300, 12)).toBe(-288); + }); + + it("allows for the visible part starting lower down than the top of the page", () => { + expect(fitShift(0, 100, 300, 200, 700, 12)).toBe(112); + }); +}); diff --git a/web/src/utils/fitInView.ts b/web/src/utils/fitInView.ts new file mode 100644 index 0000000..ca0154a --- /dev/null +++ b/web/src/utils/fitInView.ts @@ -0,0 +1,19 @@ +/** + * How far a box that is `shift` down from where it would otherwise sit (negative is up) needs to be + * moved to be seen between the top and the bottom of what is visible, with `margin` to spare. The + * `top` and `height` are those of the box without the shift. A box that is in view already is left + * where it is, rather than brought back to the middle, so this is only ever what is needed. + */ +export function fitShift( + shift: number, + top: number, + height: number, + visibleTop: number, + visibleBottom: number, + margin: number, +): number { + const furthestUp = visibleTop + margin - top; + const furthestDown = visibleBottom - margin - (top + height); + // If it is too tall to fit, the top of it is what is kept in view + return Math.max(furthestUp, Math.min(furthestDown, shift)); +}