From ed4fcf62a5dfe5c8108dbc2edb2f243f871c0fe9 Mon Sep 17 00:00:00 2001 From: SylvainDruaux Date: Mon, 23 Nov 2026 20:59:47 +0100 Subject: [PATCH 1/3] fix(preview): canvas frames keep the breakpoint's whole width A canvas frame drew Chromium's own scrollbar, which takes about 15px of the page on a computer with classic scrollbars, so a 320px phone frame laid its page out in 305px while its media queries still read 320, and text wrapped where it never does on a phone. Frames now draw no root scrollbar: the page gets the frame's whole width at every breakpoint, as on a real phone or tablet. The canvas draws its own thin scrollbar instead, as Webflow does: a solid 5px thumb 2px outside the frame, always visible and draggable, never over the page. Desktop's frame keeps a 9px gutter on each side for it, and the toolbar and the style panel read the page width that remains. Settings > Editor > Canvas can give Chromium's real scrollbar back from a breakpoint up: "Laptop and wider", "Desktop and wider" or any wider breakpoint the project has, by its own name. Tablets and phones are not offered, since their own scrollbar floats over the page. Desktop starts one pixel past the widest narrower breakpoint, so the choices follow the project's breakpoints however many there are. The preference's parser is a module of its own, so the IPC contract graph grows by one module rather than by the whole scrollbar module. Tests that pinned Desktop at the pane's full width now expect the width less the two gutters. --- docs/contracts.md | 22 ++ electron/app/mainValidation.ts | 5 + electron/main.ts | 12 +- electron/preload/frameQueries.ts | 4 + electron/preload/frameScrollbar.ts | 197 +++++++++++++ electron/preload/preload.ts | 4 + shared/ipc/ipcPayloads.ts | 4 +- shared/ipc/preferences.ts | 22 +- shared/properties/canvasScrollbar.ts | 275 ++++++++++++++++++ shared/properties/canvasScrollbarChoice.ts | 48 +++ .../properties/i18n/messages/ar/settings.ts | 6 + .../properties/i18n/messages/de/settings.ts | 6 + .../properties/i18n/messages/en/settings.ts | 6 + .../properties/i18n/messages/es/settings.ts | 6 + .../properties/i18n/messages/fr/settings.ts | 6 + .../properties/i18n/messages/he/settings.ts | 6 + .../properties/i18n/messages/hi/settings.ts | 6 + .../properties/i18n/messages/id/settings.ts | 6 + .../properties/i18n/messages/it/settings.ts | 6 + .../properties/i18n/messages/ja/settings.ts | 6 + .../properties/i18n/messages/ko/settings.ts | 6 + .../properties/i18n/messages/nl/settings.ts | 6 + .../properties/i18n/messages/pl/settings.ts | 6 + .../properties/i18n/messages/ptBR/settings.ts | 6 + .../properties/i18n/messages/ru/settings.ts | 6 + .../properties/i18n/messages/tr/settings.ts | 6 + .../properties/i18n/messages/zhCN/settings.ts | 6 + .../properties/i18n/messages/zhTW/settings.ts | 6 + src/app/settings/CanvasScrollbarSetting.tsx | 67 +++++ src/app/settings/Settings.tsx | 19 +- src/app/settings/preferencesBridge.ts | 4 +- src/app/shell/AppShell.tsx | 5 +- src/features/preview/CanvasScrollbar.tsx | 147 ++++++++++ src/features/preview/PreviewPane.tsx | 13 +- src/features/preview/SizedFrame.tsx | 25 +- .../preview/canvasScrollbarPreference.ts | 67 +++++ src/features/preview/previewViewport.css | 24 ++ src/features/preview/previewViewport.ts | 15 +- src/features/preview/usePreviewSizing.ts | 6 +- studio/scripts/shared-source.json | 4 + .../features/preview/InteractivePreview.tsx | 3 +- studio/src/features/preview/PreviewCanvas.tsx | 3 +- studio/src/features/preview/previewClient.ts | 6 + test/electron/app/mainBoundaries.test.ts | 22 ++ .../preload/canvasScrollbarChromium.test.js | 169 +++++++++++ test/electron/preload/frameScrollbar.test.js | 215 ++++++++++++++ test/renderer/ai/reviewChanges.test.js | 1 + test/renderer/ai/untrackedChanges.test.js | 1 + test/renderer/preview/canvasScrollbar.test.js | 209 +++++++++++++ .../preview/desktopDeviceBase.test.js | 27 +- .../preview/desktopDeviceChromium.test.js | 18 +- test/renderer/preview/panelDragHold.test.js | 11 +- .../renderer/preview/previewLifecycle.test.js | 6 +- .../preview/resizeHandlesModes.test.js | 2 +- test/renderer/style/codeChips.test.js | 1 + test/shared/ipc/preferences.test.ts | 44 ++- .../shared/properties/canvasScrollbar.test.ts | 174 +++++++++++ 57 files changed, 1951 insertions(+), 58 deletions(-) create mode 100644 electron/preload/frameScrollbar.ts create mode 100644 shared/properties/canvasScrollbar.ts create mode 100644 shared/properties/canvasScrollbarChoice.ts create mode 100644 src/app/settings/CanvasScrollbarSetting.tsx create mode 100644 src/features/preview/CanvasScrollbar.tsx create mode 100644 src/features/preview/canvasScrollbarPreference.ts create mode 100644 test/electron/preload/canvasScrollbarChromium.test.js create mode 100644 test/electron/preload/frameScrollbar.test.js create mode 100644 test/renderer/preview/canvasScrollbar.test.js create mode 100644 test/shared/properties/canvasScrollbar.test.ts diff --git a/docs/contracts.md b/docs/contracts.md index b3e48fee6..d64d3597c 100644 --- a/docs/contracts.md +++ b/docs/contracts.md @@ -615,6 +615,18 @@ the value cache's selection and history invalidation and never becomes editable not a `replay`: a freshly reloaded page posts its click late, and the click ladder's replay is the same press answered again, so either used to close what the person had opened since (soak SP-04). A press without `pressedAtMs` (Studio's preview client) is taken at its word. +- The page's scrollbar (`shared/properties/canvasScrollbar.ts`, frame half `electron/preload/frameScrollbar.ts`, + canvas half `src/features/preview/CanvasScrollbar.tsx`). A canvas frame scrolls inside itself, and Chromium's + classic scrollbar there took about 15px from the page (a 320px phone frame laid out in 305px while its media + queries read 320). Every sized frame (`SizedFrame`: the canvas, interact mode and preview mode, Desktop and Studio) + is told on each page load `avb:canvas-scrollbar` `{ chromiumFromPx? }` (a whole canvas width within the breakpoint + bounds; absent: none); the frame hides its root scrollbar (`scrollbar-width: none`) everywhere or below that width + with a media query, so a resize across it switches without a message. The frame reports `avb:page-scroll` + `{ topPx, heightPx, viewHeightPx, chromium }` (finite, never negative, at most `pagePxMax`) at most once per + animation frame and only when it changed: on scroll, resize, load, `avb:morphed` and a change of the page's height; + `chromium` stays true until the app's word arrives, so the canvas never draws a second bar. The canvas draws its own + thin bar from it, outside a framed device and over the page's right edge on a full frame, and a press or drag on it + sends `avb:page-scroll-to` `{ topPx }`, which the frame scrolls to at once. Only the root scrollbar is touched. - `preview:check` `{ projectPath, render }` → `PreviewVerdict`: main re-derives the token from the manifest, then reads every stamped file from disk (`electron/preview/previewCheck.ts`; a path outside the project is `missing`, a file @@ -1023,6 +1035,16 @@ value (`src/features/style/codeChips/`). It changes only what is drawn: the text are the CSS as written. Turned off, each open editor shows plain CSS at once. Studio and the demo have no app settings file and keep the default. +`canvasScrollbar` (Settings > Editor > Canvas, "Chromium scrollbar"; default `off`, kept per person in +`settings.json`) is the one preference that is not on or off: `off`, or a breakpoint id, meaning that +breakpoint and every wider frame. `settings:set` carries it as `{ setting: 'canvasScrollbar', value }` +(`parsePreferenceChange`, `shared/ipc/preferences.ts`), every other preference as `{ setting, enabled }`; +the value is the stored text, so the renderer's parsed payload parses again unchanged in main. Off, the +canvas draws its own thin scrollbar beside every frame and the page gets the breakpoint's whole width, +as on a phone; from a breakpoint, frames at its canvas width and wider keep Chromium's own scrollbar, as +a desktop browser with a mouse does. A breakpoint the open project does not have reads as Off. Studio and +the demo keep Off. + ## Interface language in the main process `locale:set` takes `{ preference }` (`"system"` or a shipped locale; anything else is refused) and returns `{ saved }`. The shipped locales are diff --git a/electron/app/mainValidation.ts b/electron/app/mainValidation.ts index 44d5c9707..e254d5f44 100644 --- a/electron/app/mainValidation.ts +++ b/electron/app/mainValidation.ts @@ -4,6 +4,7 @@ import { boolean, count, data, dictionary, list, nullable, object, optional, pat import type { Data } from '../../shared/core/boundary'; import type { LocalePreference } from '../../shared/core/i18n/locales'; import { parseAutoCompactPercent } from '../../shared/properties/ai/autoCompact'; +import { CANVAS_SCROLLBAR_DEFAULT, canvasScrollbarPreferenceText, parseCanvasScrollbarPreference } from '../../shared/properties/canvasScrollbarChoice'; import { parseLocalePreferenceValue } from '../../shared/ipc/localeChannel'; import type { ContentCollection } from '../content/contentEntries'; import type { DynamicEntry } from '../lib/mainTypes'; @@ -27,6 +28,8 @@ export interface AppSettings { readonly aiAutoCompactPercent?: number; /** Draw CSS values in code editors as chips (variables, easings, shadows, gradients, clip-paths); on unless turned off. */ readonly codeChips: boolean; + /** Where Chromium's own scrollbar starts on the canvas: `off` (the canvas's bar everywhere) or a breakpoint id (canvasScrollbar.ts). */ + readonly canvasScrollbar: string; /** The interface language the renderer last chose (docs/i18n-playbook.md, "Main process"); "system" follows the operating system. */ readonly localePreference: LocalePreference; } @@ -43,6 +46,7 @@ export function parseSettings(input: unknown): AppSettings { aiReviewChanges: optional(boolean), aiAutoCompactPercent: optional(parseAutoCompactPercent), codeChips: optional(boolean), + canvasScrollbar: optional(parseCanvasScrollbarPreference), localePreference: optional(parseLocalePreferenceValue), })(input); if (value.usageNoticeVersion !== undefined && value.usageNoticeVersion > 10) { @@ -60,6 +64,7 @@ export function parseSettings(input: unknown): AppSettings { aiTrackChanges: value.aiTrackChanges ?? true, aiReviewChanges: value.aiReviewChanges ?? false, codeChips: value.codeChips ?? true, + canvasScrollbar: canvasScrollbarPreferenceText(value.canvasScrollbar ?? CANVAS_SCROLLBAR_DEFAULT), localePreference: value.localePreference ?? 'system', ...(value.usageLastAttemptDay === undefined ? {} : { usageLastAttemptDay: value.usageLastAttemptDay }), ...(value.aiAutoCompactPercent === undefined ? {} : { aiAutoCompactPercent: value.aiAutoCompactPercent }), diff --git a/electron/main.ts b/electron/main.ts index 2c9c219c9..004dc861c 100644 --- a/electron/main.ts +++ b/electron/main.ts @@ -69,6 +69,8 @@ import { activeMainLocale, loadMainLocale, setMainLocale, translateMain } from ' import { openMicrophoneSettings, microphoneStatus, requestMicrophone, type MicrophoneSystem } from './app/microphoneAccess'; import { LOCALE_PREFERENCE_DEFAULT } from '../shared/core/i18n/locales'; import { resolveLocale } from '../shared/core/i18n/parseLocale'; +import { CANVAS_SCROLLBAR_DEFAULT, canvasScrollbarPreferenceText } from '../shared/properties/canvasScrollbarChoice'; +import { CANVAS_SCROLLBAR_SETTING } from '../shared/ipc/preferences'; import { registerTerminalHandlers, cleanupTerminals } from './terminal/terminal'; import { watchProject } from './project/projectWatcher'; import { watchInstructions } from './project/instructionsWatcher'; @@ -912,6 +914,8 @@ const SETTINGS_DEFAULTS: AppSettings = { aiReviewChanges: false, // On: CSS in code editors shows variables, easings, shadows, gradients and clip-paths as chips that open their editors. codeChips: true, + // Off: the canvas draws its own scrollbar beside every frame, so the page always has the breakpoint's whole width. + canvasScrollbar: canvasScrollbarPreferenceText(CANVAS_SCROLLBAR_DEFAULT), localePreference: LOCALE_PREFERENCE_DEFAULT, }; let settings: AppSettings = { ...SETTINGS_DEFAULTS }; @@ -956,9 +960,15 @@ const publicSettings = () => ({ aiTrackChanges: settings.aiTrackChanges, aiReviewChanges: settings.aiReviewChanges, codeChips: settings.codeChips, + canvasScrollbar: settings.canvasScrollbar, }); ipcMain.handle('settings:get', publicSettings); -ipcMain.handle('settings:set', (_event, { setting, enabled }) => { +ipcMain.handle('settings:set', (_event, change) => { + if (change.setting === CANVAS_SCROLLBAR_SETTING) { + settings = { ...settings, canvasScrollbar: change.value }; + return { ...publicSettings(), saved: writeSettings() }; + } + const { setting, enabled } = change; let saved: boolean; if (setting === 'sound') { settings = { ...settings, sound: enabled }; diff --git a/electron/preload/frameQueries.ts b/electron/preload/frameQueries.ts index 668b431c8..90686951f 100644 --- a/electron/preload/frameQueries.ts +++ b/electron/preload/frameQueries.ts @@ -4,6 +4,7 @@ import { receiveAppCursor } from './frameAppCursor'; import { receivePointQuery } from './framePointQuery'; import { receiveOutlineMode } from './frameOutlineMode'; import { receiveAppScroll, receiveAppWheel } from './frameAppScroll'; +import { receiveCanvasScrollbar } from './frameScrollbar'; import { parseCanvasInteraction, parseCanvasSitePages } from '../../shared/properties/canvasInteraction'; import { clearPendingDeletes, hidePendingDelete, listenForPendingDeletes } from './framePendingDelete'; import { listenForCanvasMoves, revertCanvasMoves, showCanvasMove } from './frameMove'; @@ -159,6 +160,9 @@ export function listenForQueries(): void { if (receiveAppCursor(data)) { return; } + if (receiveCanvasScrollbar(data)) { + return; + } if (data['type'] === 'avb:click-query') { receiveClickQuery(data); return; diff --git a/electron/preload/frameScrollbar.ts b/electron/preload/frameScrollbar.ts new file mode 100644 index 000000000..af5d5804d --- /dev/null +++ b/electron/preload/frameScrollbar.ts @@ -0,0 +1,197 @@ +// The frame's half of the canvas scrollbar (shared/properties/canvasScrollbar.ts), shared by Desktop's preload +// (frameQueries.ts) and Studio's preview client: hides the page's root scrollbar where the app says, reports the +// page's vertical scroll so the canvas can draw its own bar, and scrolls when that bar is dragged. +// +// Until the app's word arrives, the page keeps Chromium's scrollbar and every report says so (`chromium: true`), +// so the canvas never draws a second bar beside a frame that still shows its own. + +import { assert } from '../../shared/core/assert'; +import { + CANVAS_SCROLLBAR_LIMITS, + canvasScrollbarCss, + chromiumScrollbarQuery, + pageScrollMessage, + parseCanvasScrollbarMessage, + parsePageScrollToMessage, + type PageScroll, +} from '../../shared/properties/canvasScrollbar'; + +const STYLE_ID = 'avb-canvas-scrollbar'; + +/** Where Chromium keeps its bar: not yet told (`unknown`, its bar everywhere), nowhere, or from a width up. */ +type ChromiumRange = { readonly kind: 'unknown' } | { readonly kind: 'query'; readonly query: MediaQueryList | undefined }; + +let range: ChromiumRange = { kind: 'unknown' }; +let post: ((message: unknown) => void) | undefined = undefined; +let reportScheduled = false; +let lastReport: PageScroll | undefined = undefined; + +/** + * Starts reporting the page's scroll to the app through `send`: on scroll and resize, after each canvas patch, and + * when the page's height changes. Once per frame: later calls are ignored. + */ +export function installPageScrollReport(send: (message: unknown) => void): void { + if (post !== undefined) { + return; + } + post = send; + window.addEventListener('scroll', scheduleReport, { passive: true }); + window.addEventListener('resize', scheduleReport); + window.addEventListener('load', scheduleReport); + document.addEventListener('avb:morphed', scheduleReport); + observeRootWhenReady(); + scheduleReport(); + assert(post === send, 'installPageScrollReport: reports go to the sender'); +} + +// A page grows without scrolling (images arriving, a patch adding a section): its height is part of the thumb, so +// is observed. It exists by the time a preload runs, but not always in a frame that is still being created +// (frameDesign.ts markFrameMode); observing a missing root throws, and a throw here would stop every frame module the +// preload installs after this one. So the observer waits for the root, at the first two moments it certainly exists. +function observeRootWhenReady(): void { + if (typeof ResizeObserver !== 'function') { + return; + } + const observer = new ResizeObserver(scheduleReport); + let observed = false; + const observe = (): void => { + const root = document.documentElement; + if (observed || root === null) { + return; + } + observer.observe(root); + observed = true; + }; + observe(); + document.addEventListener('readystatechange', observe); + window.addEventListener('DOMContentLoaded', observe); +} + +/** Applies an app message if it is one (where Chromium's bar starts, or a scroll); false when it was something else. */ +export function receiveCanvasScrollbar(input: unknown): boolean { + const scrollbar = parseCanvasScrollbarMessage(input); + if (scrollbar !== undefined) { + applyRange(scrollbar.chromiumFromPx); + return true; + } + const scrollTo = parsePageScrollToMessage(input); + if (scrollTo !== undefined) { + window.scrollTo({ top: scrollTo.topPx, behavior: 'instant' }); + scheduleReport(); + return true; + } + return false; +} + +/** The scroll the frame reports now, or undefined before the page has a root to scroll. */ +export function pageScrollNow(): PageScroll | undefined { + const root = document.scrollingElement ?? document.documentElement; + if (root === null) { + return undefined; // A frame still being created: its first report comes once the page exists. + } + const scroll = { + topPx: clampPagePx(root.scrollTop), + heightPx: clampPagePx(root.scrollHeight), + viewHeightPx: clampPagePx(window.innerHeight), + chromium: chromiumDrawsBar(), + }; + assert(scroll.topPx >= 0, 'pageScrollNow: never above the page'); + assert(scroll.viewHeightPx >= 0, 'pageScrollNow: a view has a height'); + return scroll; +} + +function applyRange(chromiumFromPx: number | undefined): void { + const style = styleElement(); + if (style === undefined) { + return; + } + const css = canvasScrollbarCss(chromiumFromPx); + if (style.textContent !== css) { + style.textContent = css; + } + if (range.kind === 'query') { + range.query?.removeEventListener('change', scheduleReport); + } + const query = chromiumScrollbarQuery(chromiumFromPx); + const list = query === undefined ? undefined : window.matchMedia(query); + list?.addEventListener('change', scheduleReport); + range = { kind: 'query', query: list }; + scheduleReport(); +} + +function chromiumDrawsBar(): boolean { + switch (range.kind) { + case 'unknown': + return true; + case 'query': + return range.query?.matches ?? false; + default: { + const exhaustive: never = range; + return exhaustive; + } + } +} + +// The one ' + + '
'; + +// The host keeps each frame's last scroll report, so the probe can read what the canvas would draw. +const HOST_PAGE = + '' + + '' + + '' + + '' + + ''; + +// What a frame's page has to lay out in, and what its last report said. +const READ_FRAMES = `(() => { + const read = (id) => { + const frame = document.getElementById(id).contentWindow; + return { innerWidth: frame.innerWidth, clientWidth: frame.document.documentElement.clientWidth, scrollY: frame.scrollY, report: window.reports[id] ?? null }; + }; + return { phone: read('phone'), desktop: read('desktop'), control: read('control') }; +})()`; + +const tell = (id, message) => `document.getElementById(${JSON.stringify(id)}).contentWindow.postMessage(${JSON.stringify(message)}, '*')`; + +(async () => { + const electronPath = (() => { + try { + return require('electron'); + } catch { + return undefined; + } + })(); + if (typeof electronPath !== 'string') { + console.log('canvas-scrollbar-chromium: skipped [needs a Chromium — see test/renderer/style/computedColor.test.js]'); + return; + } + const preload = repoPath('dist/electron/preload/preload.js'); + check('the preload is built', fs.existsSync(preload), preload); + + const server = http.createServer((request, response) => { + const url = new URL(request.url || '/', 'http://127.0.0.1'); + response.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }); + response.end(url.pathname === '/frame.html' ? FRAME_PAGE : HOST_PAGE); + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + const address = server.address(); + const port = typeof address === 'object' && address !== null ? address.port : 0; + + const probeDirectory = repoPath('node_modules/.stacki-test/canvas-scrollbar-chromium'); + fs.mkdirSync(probeDirectory, { recursive: true }); + const probe = path.join(probeDirectory, 'probe.js'); + fs.writeFileSync( + probe, + `const { app, BrowserWindow, ipcMain } = require('electron'); + app.disableHardwareAcceleration(); + // The preload's top frame asks main for the boot seed synchronously (electron/boot/bootChannels.ts). + ipcMain.on('boot:read', (event) => { + event.returnValue = undefined; + }); + app.on('window-all-closed', () => app.quit()); + const { waitFor } = require(${JSON.stringify(repoPath('test/helpers/waitFor.js'))}); + app.whenReady().then(async () => { + const win = new BrowserWindow({ + show: false, width: 3400, height: 800, + webPreferences: { preload: ${JSON.stringify(preload)}, contextIsolation: true, nodeIntegration: false, nodeIntegrationInSubFrames: true }, + }); + const run = (code) => win.webContents.executeJavaScript(code); + const read = () => run(${JSON.stringify(READ_FRAMES)}); + await win.loadURL('http://127.0.0.1:${port}/host.html'); + // Each frame reports once its preload runs: Chromium's bar until the app's word arrives. + const before = await waitFor({ what: 'every frame reports', read, until: (frames) => frames.phone.report && frames.desktop.report && frames.control.report }); + await run(${JSON.stringify(tell('phone', { type: 'avb:canvas-scrollbar', chromiumFromPx: 1023 }))}); + await run(${JSON.stringify(tell('desktop', { type: 'avb:canvas-scrollbar', chromiumFromPx: 1023 }))}); + const told = await waitFor({ what: 'the phone frame reports the canvas bar', read, until: (frames) => frames.phone.report.chromium === false }); + await run(${JSON.stringify(tell('phone', { type: 'avb:page-scroll-to', topPx: 500 }))}); + const scrolled = await waitFor({ what: 'the phone frame scrolls', read, until: (frames) => frames.phone.report.topPx === 500 }); + await run(${JSON.stringify(tell('desktop', { type: 'avb:canvas-scrollbar' }))}); + const off = await waitFor({ what: 'the desktop frame reports Off', read, until: (frames) => frames.desktop.report.chromium === false }); + console.log(JSON.stringify({ before, told, scrolled, off })); + app.quit(); + });`, + ); + + const environment = { ...process.env }; + delete environment.ELECTRON_RUN_AS_NODE; + // Asynchronous, so this process keeps serving the pages the probe loads. + const run = await new Promise((resolve) => { + const child = spawn(electronPath, [probe], { env: environment }); + let stdout = ''; + let stderr = ''; + child.stdout.on('data', (chunk) => (stdout += chunk)); + child.stderr.on('data', (chunk) => (stderr += chunk)); + // Only a ceiling for a hung probe: the checks take as long as the machine needs. + const timer = setTimeout(() => child.kill(), 180000); + child.on('exit', () => { + clearTimeout(timer); + resolve({ stdout, stderr }); + }); + }); + server.close(); + + const line = run.stdout.split('\n').find((text) => text.trim().startsWith('{')); + if (!line) { + check('the browser probe ran', false, (run.stderr || run.stdout || '').slice(0, 3000)); + } else { + const { before, told, scrolled, off } = JSON.parse(line); + const detail = (frame) => JSON.stringify(frame); + check('before the app’s word, every frame says Chromium draws its bar', before.phone.report.chromium && before.control.report.chromium, detail(before)); + check('a 320px phone frame lays its page out at 320px', told.phone.innerWidth === 320 && told.phone.clientWidth === 320, detail(told.phone)); + check('and says the canvas draws its bar', told.phone.report.chromium === false, detail(told.phone)); + check( + 'a 1440px frame past Laptop keeps exactly the bar Chromium draws in an untouched frame', + told.desktop.clientWidth === told.control.clientWidth, + `${detail(told.desktop)} vs ${detail(told.control)}`, + ); + check('and says Chromium draws it', told.desktop.report.chromium === true, detail(told.desktop)); + check( + 'the canvas bar’s scroll moves the page and is reported', + scrolled.phone.scrollY === 500 && scrolled.phone.report.topPx === 500, + detail(scrolled.phone), + ); + check('Off gives a 1440px frame its whole width', off.desktop.clientWidth === off.desktop.innerWidth, detail(off.desktop)); + } + + if (failures.length) { + console.error(`canvas-scrollbar-chromium: ${failures.length} of ${checked} failed\n${failures.join('\n')}`); + process.exit(1); + } + console.log(`canvas-scrollbar-chromium: ${checked} passed [a frame below the Chromium width gets its whole width; one past it keeps Chromium's bar]`); + process.exit(0); +})().catch((error) => { + console.error(error); + process.exit(1); +}); diff --git a/test/electron/preload/frameScrollbar.test.js b/test/electron/preload/frameScrollbar.test.js new file mode 100644 index 000000000..c0a7c0261 --- /dev/null +++ b/test/electron/preload/frameScrollbar.test.js @@ -0,0 +1,215 @@ +// Goal: the frame half of the canvas scrollbar (electron/preload/frameScrollbar.ts) hides the page's root scrollbar +// exactly where the app says, tells the truth about which bar is drawn (Chromium's until the app's word arrives), reports +// the page's scroll at most once per animation frame and only when it changed, and scrolls when the canvas's bar asks. +// Method: the real module, bundled with esbuild, runs in a fresh jsdom window per test (its state is per page, as in a +// frame). jsdom has no layout, so the test owns the root's scroll position and height and a `matchMedia` that answers +// from a width the test sets; animation frames are queued and flushed by hand. Every report is read through the shared +// contract's parser, as the canvas reads it. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const vm = require('node:vm'); +const { buildSync } = require('esbuild'); +const { JSDOM } = require('jsdom'); +const { repoPath } = require('../../helpers/sources'); +const loadRenderer = require('../../helpers/rendererModule'); +const { parsePageScrollMessage } = loadRenderer('shared/properties/canvasScrollbar.ts'); + +let bundle; +function moduleSource() { + bundle ??= buildSync({ + entryPoints: [repoPath('electron/preload/frameScrollbar.ts')], + bundle: true, + platform: 'browser', + format: 'iife', + globalName: 'FrameScrollbarModule', + write: false, + logLevel: 'silent', + }).outputFiles[0].text; + return bundle; +} + +// A frame `widthPx` wide holding a page `heightPx` tall, the module loaded and reporting into `sent`. +function frame({ widthPx, heightPx }) { + const dom = new JSDOM(''); + const window = dom.window; + const root = window.document.documentElement; + const page = { widthPx, heightPx, topPx: 0 }; + Object.defineProperty(root, 'scrollTop', { configurable: true, get: () => page.topPx }); + Object.defineProperty(root, 'scrollHeight', { configurable: true, get: () => page.heightPx }); + Object.defineProperty(window, 'innerHeight', { configurable: true, get: () => 800 }); + const queries = []; + window.matchMedia = (query) => { + const atLeast = Number(/^\(width >= (\d+)px\)$/.exec(query)?.[1]); + assert.ok(Number.isSafeInteger(atLeast), `a width query: ${query}`); + const listeners = new Set(); + const list = { + get matches() { + return page.widthPx >= atLeast; + }, + addEventListener: (_type, listener) => listeners.add(listener), + removeEventListener: (_type, listener) => listeners.delete(listener), + listeners, + }; + queries.push(list); + return list; + }; + const scrolls = []; + window.scrollTo = (options) => { + scrolls.push(options); + page.topPx = Math.max(0, Math.min(page.heightPx - 800, options.top)); + }; + let queued = []; + const context = { + window, + document: window.document, + HTMLStyleElement: window.HTMLStyleElement, + requestAnimationFrame: (callback) => { + queued.push(callback); + return queued.length; + }, + ResizeObserver: class { + observe() {} + }, + }; + vm.runInNewContext(moduleSource(), context); + const module = context.FrameScrollbarModule; + const sent = []; + return { + module, + window, + page, + queries, + scrolls, + sent, + install: () => module.installPageScrollReport((message) => sent.push(message)), + // Runs the animation frames queued so far, as the browser would before its next paint. + flush: () => { + const callbacks = queued; + queued = []; + for (const callback of callbacks) { + callback(); + } + }, + sheet: () => window.document.getElementById('avb-canvas-scrollbar')?.textContent, + // The reports sent so far, read through the shared parser as the canvas reads them. + reports: () => + sent.map((message) => { + const parsed = parsePageScrollMessage(message); + assert.ok(parsed, `a report the canvas accepts: ${JSON.stringify(message)}`); + return parsed; + }), + scroll: (topPx) => { + page.topPx = topPx; + window.dispatchEvent(new window.Event('scroll')); + }, + close: () => window.close(), + }; +} + +test('until the app says where Chromium’s bar starts, the page keeps it and every report says so', (context) => { + const view = frame({ widthPx: 320, heightPx: 4000 }); + context.after(view.close); + view.install(); + view.flush(); + assert.equal(view.sheet(), undefined, 'nothing is hidden before the app’s word'); + assert.deepEqual(view.reports(), [{ type: 'avb:page-scroll', topPx: 0, heightPx: 4000, viewHeightPx: 800, chromium: true }]); +}); + +test('Off hides the root bar at every width, and the canvas draws its own', (context) => { + const view = frame({ widthPx: 1440, heightPx: 4000 }); + context.after(view.close); + view.install(); + assert.equal(view.module.receiveCanvasScrollbar({ type: 'avb:canvas-scrollbar' }), true); + view.flush(); + assert.equal(view.sheet(), 'html { scrollbar-width: none !important; }'); + assert.equal(view.reports().at(-1).chromium, false); + assert.equal(view.queries.length, 0, 'no width to watch'); +}); + +test('from a breakpoint, a frame below it hides the root bar and one at or past it keeps Chromium’s, as it is dragged', (context) => { + const view = frame({ widthPx: 320, heightPx: 4000 }); + context.after(view.close); + view.install(); + view.module.receiveCanvasScrollbar({ type: 'avb:canvas-scrollbar', chromiumFromPx: 1023 }); + view.flush(); + assert.equal(view.sheet(), '@media (width < 1023px) { html { scrollbar-width: none !important; } }'); + assert.equal(view.reports().at(-1).chromium, false, 'a phone frame: the canvas draws the bar'); + // The frame is dragged to the Laptop width: the media query changes and the frame says so without a message. + view.page.widthPx = 1023; + for (const listener of view.queries[0].listeners) { + listener(); + } + view.flush(); + assert.equal(view.reports().at(-1).chromium, true, 'Laptop and wider: Chromium draws its own'); + // Turned off again: the old width is no longer watched. + view.module.receiveCanvasScrollbar({ type: 'avb:canvas-scrollbar' }); + view.flush(); + assert.equal(view.queries[0].listeners.size, 0, 'the previous query is let go'); + assert.equal(view.sheet(), 'html { scrollbar-width: none !important; }'); + assert.equal(view.reports().at(-1).chromium, false); +}); + +test('a burst of scrolls is one report per animation frame, and an unchanged page sends none', (context) => { + const view = frame({ widthPx: 320, heightPx: 4000 }); + context.after(view.close); + view.install(); + view.install(); // A second install is ignored: one listener, one report per change. + view.module.receiveCanvasScrollbar({ type: 'avb:canvas-scrollbar' }); + view.flush(); + const before = view.sent.length; + view.scroll(100); + view.scroll(200); + view.scroll(300); + view.flush(); + assert.equal(view.sent.length, before + 1, 'three scrolls in one frame: one report'); + assert.equal(view.reports().at(-1).topPx, 300); + view.scroll(300); + view.flush(); + assert.equal(view.sent.length, before + 1, 'the same scroll again: nothing new to draw'); + // The page grows under a canvas patch, with no scroll: the morph's event is enough for a new report. + view.page.heightPx = 6000; + view.window.document.dispatchEvent(new view.window.Event('avb:morphed')); + view.flush(); + assert.equal(view.sent.length, before + 2); + assert.equal(view.reports().at(-1).heightPx, 6000); +}); + +test('the canvas’s bar scrolls the page, and the new position is reported', (context) => { + const view = frame({ widthPx: 320, heightPx: 4000 }); + context.after(view.close); + view.install(); + view.module.receiveCanvasScrollbar({ type: 'avb:canvas-scrollbar' }); + view.flush(); + assert.equal(view.module.receiveCanvasScrollbar({ type: 'avb:page-scroll-to', topPx: 1600 }), true); + // The options were made in the frame's own realm: compared by their fields, not their prototype. + assert.equal(view.scrolls.length, 1); + assert.equal(view.scrolls[0].top, 1600); + assert.equal(view.scrolls[0].behavior, 'instant', 'instant: a smooth-scroll library on the page does not trail the thumb'); + view.flush(); + assert.equal(view.reports().at(-1).topPx, 1600); +}); + +test('anything else is not this module’s, and a malformed width hides nothing', (context) => { + const view = frame({ widthPx: 320, heightPx: 4000 }); + context.after(view.close); + for (const input of [ + undefined, + { type: 'avb:query' }, + { type: 'avb:canvas-scrollbar', chromiumFromPx: 12 }, + { type: 'avb:canvas-scrollbar', chromiumFromPx: '1023' }, + { type: 'avb:page-scroll-to', topPx: -1 }, + { type: 'avb:page-scroll-to' }, + ]) { + assert.equal(view.module.receiveCanvasScrollbar(input), false, JSON.stringify(input)); + } + assert.equal(view.sheet(), undefined); + assert.deepEqual(view.scrolls, []); +}); + +test('a page taller than the bound is reported at the bound, never as an invalid report', (context) => { + const view = frame({ widthPx: 320, heightPx: 50_000_000 }); + context.after(view.close); + view.install(); + view.flush(); + assert.equal(view.reports().at(-1).heightPx, 10_000_000); +}); diff --git a/test/renderer/ai/reviewChanges.test.js b/test/renderer/ai/reviewChanges.test.js index 56bfdf499..be071659e 100644 --- a/test/renderer/ai/reviewChanges.test.js +++ b/test/renderer/ai/reviewChanges.test.js @@ -21,6 +21,7 @@ function fakePreferences({ stored, failSet = false }) { aiTrackChanges: true, aiReviewChanges, codeChips: true, + canvasScrollbar: 'off', }); window.avb = { settings: async () => everything(stored), diff --git a/test/renderer/ai/untrackedChanges.test.js b/test/renderer/ai/untrackedChanges.test.js index 6a9eabd68..d89817f99 100644 --- a/test/renderer/ai/untrackedChanges.test.js +++ b/test/renderer/ai/untrackedChanges.test.js @@ -48,6 +48,7 @@ const saved = (enabled) => ({ aiTrackChanges: enabled, aiReviewChanges: false, codeChips: true, + canvasScrollbar: 'off', saved: true, }); diff --git a/test/renderer/preview/canvasScrollbar.test.js b/test/renderer/preview/canvasScrollbar.test.js new file mode 100644 index 000000000..ce8bf5746 --- /dev/null +++ b/test/renderer/preview/canvasScrollbar.test.js @@ -0,0 +1,209 @@ +// Goal: the canvas's own scrollbar (src/features/preview/CanvasScrollbar.tsx) tells each page where Chromium's bar +// starts, draws a thumb only for a page that scrolls and only where Chromium draws none, sits in the gutter just outside +// the frame (never over the page) at a constant on-screen size, and scrolls the page when the track is +// pressed or the thumb dragged. +// Method: the real component, bundled with esbuild, is mounted in jsdom next to a real iframe inside the frame holder, +// as SizedFrame mounts it. What it posts to the iframe is captured; the frame's reports are MessageEvents whose source +// is the iframe's window, as in the app. jsdom has no layout, so the track's box is at the origin and every position +// is read from the inline styles the component writes. Presses and drags are pointer events on the track and the +// window, as usePointerDrag listens; animation frames are held and run by each pointer step, never waited for. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const esbuild = require('esbuild'); +const { JSDOM } = require('jsdom'); +const { ROOT, repoPath } = require('../../helpers/sources.js'); + +const directory = repoPath('node_modules/.stacki-test/canvas-scrollbar'); +fs.mkdirSync(directory, { recursive: true }); +esbuild.buildSync({ + stdin: { + contents: "export { CanvasScrollbar } from './src/features/preview/CanvasScrollbar.tsx';", + resolveDir: ROOT, + loader: 'jsx', + }, + outfile: path.join(directory, 'scrollbar.js'), + bundle: true, + format: 'cjs', + platform: 'node', + external: ['react', 'react-dom', 'react-dom/client', 'react/jsx-runtime'], + loader: { '.css': 'empty' }, + logLevel: 'silent', +}); + +const frames = new Map(); +let frameCount = 0; +// Runs the held animation frames, those they ask for in turn included; bounded, as a drag asks one frame per step. +const runFrames = () => { + for (let round = 0; round < 10 && frames.size > 0; round += 1) { + const due = [...frames.values()]; + frames.clear(); + for (const callback of due) { + callback(performance.now()); + } + } +}; +const REPORT = { type: 'avb:page-scroll', topPx: 1600, heightPx: 4000, viewHeightPx: 800, chromium: false }; + +function installDOM() { + const dom = new JSDOM('
', { url: 'http://localhost/', pretendToBeVisual: true }); + const { window } = dom; + for (const key of [ + 'window', + 'document', + 'navigator', + 'HTMLElement', + 'HTMLIFrameElement', + 'Element', + 'Node', + 'MutationObserver', + 'CustomEvent', + 'MessageEvent', + ]) { + global[key] = key === 'window' ? window : window[key]; + } + // Animation frames are held, and each pointer step runs the ones it asked for (`runFrames`), so no test guesses a delay. + frames.clear(); + global.requestAnimationFrame = (callback) => { + frameCount += 1; + frames.set(frameCount, callback); + return frameCount; + }; + global.cancelAnimationFrame = (id) => frames.delete(id); + global.IS_REACT_ACT_ENVIRONMENT = true; + return dom; +} + +// Mounts the bar in a frame holder with an iframe, as SizedFrame does; `props` are the bar's own. +async function mount(props) { + const dom = installDOM(); + const React = require('react'); + const { act } = React; + const { createRoot } = require('react-dom/client'); + const { CanvasScrollbar } = require(path.join(directory, 'scrollbar.js')); + const holder = { current: undefined }; + let current = props; + function Frame() { + const frameRef = React.useRef(undefined); + holder.current = frameRef; + return React.createElement( + 'div', + { ref: frameRef, className: 'frame-sized' }, + React.createElement('iframe', { title: 'Site', src: 'http://localhost:4321/#avb-design' }), + React.createElement(CanvasScrollbar, { frameRef, ...current }), + ); + } + const root = createRoot(document.getElementById('root')); + await act(async () => root.render(React.createElement(Frame))); + const iframe = document.querySelector('iframe'); + const posted = []; + iframe.contentWindow.postMessage = (message, origin) => posted.push({ message, origin }); + return { + dom, + posted, + iframe, + frame: () => holder.current.current, + rerender: async (next) => { + current = { ...current, ...next }; + await act(async () => root.render(React.createElement(Frame))); + }, + // A report from the page in the iframe, or from `source` when another window sends it. + report: async (data, source = iframe.contentWindow) => { + await act(async () => { + window.dispatchEvent(new window.MessageEvent('message', { data, source })); + }); + }, + load: async () => { + await act(async () => { + iframe.dispatchEvent(new window.Event('load')); + }); + }, + // The DOM answers null for "none": converted here, where it is read. + bar: () => document.querySelector('.canvas-scrollbar') ?? undefined, + thumb: () => document.querySelector('.canvas-scrollbar-thumb') ?? undefined, + pointer: async (target, type, clientY) => { + await act(async () => { + target.dispatchEvent(new window.MouseEvent(type, { bubbles: true, cancelable: true, button: 0, clientY })); + runFrames(); + }); + }, + close: async () => { + await act(async () => root.unmount()); + dom.window.close(); + }, + }; +} + +const px = (value) => Number.parseFloat(value); + +test('each page is told where Chromium’s bar starts: on mount, on every load, and when the setting changes', async (context) => { + const view = await mount({ scale: 1, chromiumFromPx: 1023 }); + context.after(view.close); + // Mounted before the spy: the first word went to the real postMessage. A load says it again. + await view.load(); + assert.deepEqual(view.posted.at(-1), { message: { type: 'avb:canvas-scrollbar', chromiumFromPx: 1023 }, origin: 'http://localhost:4321' }); + await view.rerender({ chromiumFromPx: undefined }); + assert.deepEqual(view.posted.at(-1).message, { type: 'avb:canvas-scrollbar' }); +}); + +test('no bar until the page reports, none where Chromium draws its own, none for a page that does not scroll', async (context) => { + const view = await mount({ scale: 1, chromiumFromPx: undefined }); + context.after(view.close); + assert.equal(view.bar(), undefined); + await view.report({ ...REPORT, chromium: true }); + assert.equal(view.bar(), undefined, 'Chromium draws its own bar'); + await view.report({ ...REPORT, heightPx: 800 }); + assert.equal(view.bar(), undefined, 'nothing to scroll'); + // Another window's report, or a malformed one, changes nothing. + await view.report(REPORT, view.dom.window); + await view.report({ ...REPORT, topPx: -1 }); + assert.equal(view.bar(), undefined); + await view.report(REPORT); + assert.ok(view.bar(), 'a page that scrolls, with no Chromium bar: the canvas draws one'); + // A new page: nothing is known of its scroll until it reports. + await view.load(); + assert.equal(view.bar(), undefined); +}); + +test('the bar sits in the gutter just outside the frame, never over the page, at the same size on screen at any zoom', async (context) => { + const view = await mount({ scale: 1, chromiumFromPx: undefined }); + context.after(view.close); + await view.report(REPORT); + // 800 of 4000 visible on the 800px track, 1600 of 3200 scrolled: a 160px thumb 320px down. + assert.equal(px(view.thumb().style.height), 160); + assert.equal(px(view.thumb().style.top), 320); + assert.equal(px(view.bar().style.width), 5); + assert.equal(px(view.bar().style.right), -7, 'in the gutter, 2px from the frame: within a fluid frame’s 9px gutter'); + // At half zoom the frame is drawn at half size: the bar's frame pixels double so the screen sees the same bar. + await view.rerender({ scale: 0.5 }); + assert.equal(px(view.bar().style.width), 10); + assert.equal(px(view.bar().style.right), -14); + await view.report({ ...REPORT, topPx: 0, heightPx: 1_000_000 }); + assert.equal(px(view.thumb().style.height), 48, 'a long page keeps a 24px thumb on screen'); +}); + +test('a press on the track jumps the thumb under the pointer, and a drag scrolls the page with it', async (context) => { + const view = await mount({ scale: 1, chromiumFromPx: undefined }); + context.after(view.close); + await view.report({ ...REPORT, topPx: 0 }); + view.posted.length = 0; + // The thumb is 0–160; a press at 600 centres it there: offset 520 of 640 to travel, 2600 of 3200 scrolled. + await view.pointer(view.bar(), 'pointerdown', 600); + assert.deepEqual(view.posted.at(-1), { message: { type: 'avb:page-scroll-to', topPx: 2600 }, origin: 'http://localhost:4321' }); + assert.ok(view.frame().classList.contains('scrolling'), 'the iframe lets the drag pass while it lasts'); + await view.pointer(view.dom.window, 'pointermove', 700); + assert.equal(view.posted.at(-1).message.topPx, 3100); + await view.pointer(view.dom.window, 'pointermove', 5000); + assert.equal(view.posted.at(-1).message.topPx, 3200, 'past the end: the end of the page'); + await view.pointer(view.dom.window, 'pointerup', 5000); + assert.ok(!view.frame().classList.contains('scrolling')); + // A press on the thumb keeps the point it was caught at: no jump, the page follows the move. + await view.report({ ...REPORT, topPx: 0 }); + view.posted.length = 0; + await view.pointer(view.bar(), 'pointerdown', 40); + assert.equal(view.posted.length, 0, 'caught where it is: nothing to jump'); + await view.pointer(view.dom.window, 'pointermove', 104); + assert.equal(view.posted.at(-1).message.topPx, 320, '64px of thumb is 320px of page'); + await view.pointer(view.dom.window, 'pointerup', 104); +}); diff --git a/test/renderer/preview/desktopDeviceBase.test.js b/test/renderer/preview/desktopDeviceBase.test.js index 3cf2e7436..e9e9d8acd 100644 --- a/test/renderer/preview/desktopDeviceBase.test.js +++ b/test/renderer/preview/desktopDeviceBase.test.js @@ -1,5 +1,5 @@ -// Goal: the Desktop device draws the page at the canvas pane's own width, never scaled or shrunk. In a narrow -// window the page renders at the pane width, so its media queries switch to the laptop, tablet or phone layout +// Goal: the Desktop device draws the page at the canvas pane's own width less the scrollbar's two 9px gutters, never +// scaled or shrunk. In a narrow window the page renders at that width, so its media queries switch to the laptop, tablet or phone layout // (as in a browser window that size). The toolbar and the style panel tell the truth about it: a pane narrower // than the Laptop canvas reads as Laptop (or Tablet, Phone), so no `< 64rem` row ever wears the Desktop icon, // and following lands on the query in effect at the pane's width. @@ -17,7 +17,7 @@ const assert = require('node:assert/strict'); const loadRenderer = require('../../helpers/rendererModule.js'); const { previewFrameWidth } = loadRenderer('src/features/preview/usePreviewSizing.ts'); -const { previewViewport } = loadRenderer('src/features/preview/previewViewport.ts'); +const { FLUID_GUTTER_PX, fluidFrameWidthPx, previewViewport } = loadRenderer('src/features/preview/previewViewport.ts'); const { activeDeviceFor, deviceForWidth } = loadRenderer('shared/properties/breakpointIcon.ts'); const { canvasTriggerIcon } = loadRenderer('src/features/style/embed/contextRows.ts'); const { followedContextKey } = loadRenderer('src/features/style/model/followWidth.ts'); @@ -70,8 +70,8 @@ function canvasAt(device, panePx, contexts) { const viewport = previewViewport(width, { width: panePx, height: PANE_HEIGHT_PX }, undefined); const key = followedContextKey(contexts, viewport.width, ROOT_FONT_SIZE_PX); const icon = canvasTriggerIcon(key, { device, widthPx: viewport.width }, BREAKPOINT_DEFAULTS); - // The canvas hook passes the frame's own width, or the pane's for a fluid frame (usePreviewSizing). - return { width, viewport, key, icon, active: activeDeviceFor(device, width ?? panePx, BREAKPOINT_DEFAULTS) }; + // The canvas hook passes the frame's own width, or the pane's less its gutters for a fluid frame (usePreviewSizing). + return { width, viewport, key, icon, active: activeDeviceFor(device, width ?? fluidFrameWidthPx(panePx), BREAKPOINT_DEFAULTS) }; } for (const [fixture, contexts] of Object.entries(FIXTURES)) { @@ -80,7 +80,7 @@ for (const [fixture, contexts] of Object.entries(FIXTURES)) { const canvas = canvasAt('desktop', panePx, contexts); const expected = DESKTOP_EXPECTED[panePx]; assert.equal(canvas.width, undefined, 'Desktop is a fluid frame: it has no width of its own'); - assert.equal(canvas.viewport.width, panePx, 'the page is as wide as the pane'); + assert.equal(canvas.viewport.width, panePx - FLUID_GUTTER_PX.side, 'the page is as wide as the pane less the scrollbar’s gutters'); assert.equal(canvas.viewport.scale, 1, 'never scaled or shrunk'); assert.equal(canvas.viewport.height, PANE_HEIGHT_PX, 'the page is as tall as the pane'); assert.equal(canvas.active, expected.device, 'the toolbar presses the device the pane width belongs to'); @@ -108,8 +108,8 @@ test('the Desktop icon is never worn at a width inside a narrower breakpoint, at for (const contexts of Object.values(FIXTURES)) { const canvas = canvasAt('desktop', panePx, contexts); assert.equal(canvas.viewport.scale, 1, `${panePx}px: Desktop never scales`); - assert.equal(canvas.viewport.width, panePx, `${panePx}px: Desktop is drawn at the pane width`); - if (panePx < 1024) { + assert.equal(canvas.viewport.width, panePx - FLUID_GUTTER_PX.side, `${panePx}px: Desktop is drawn at the pane width less its gutters`); + if (canvas.viewport.width < 1024) { assert.notEqual(canvas.active, 'desktop', `${panePx}px is inside a narrower breakpoint, so the bar cannot say Desktop`); assert.notEqual(canvas.icon, 'desktop', `${panePx}px: no row wears the Desktop icon`); } else { @@ -182,11 +182,16 @@ test('other devices keep their own widths and a custom width stays custom', () = assert.equal(previewFrameWidth('laptop', 900, BREAKPOINT_DEFAULTS), 1023, 'a stale custom width is never read on a device'); }); -// A fluid frame covers the pane at scale 1 and reserves no gutter; a fixed width keeps the framed 24px and 32px gutters. -test('previewViewport: a fluid frame covers the pane, a fixed one leaves its gutter', () => { +// A fluid frame fills the pane's height at scale 1 and keeps 9px each side for the scrollbar; a fixed width keeps the +// framed 24px and 32px gutters. An unmeasured or tiny pane never gives a negative width. +test('previewViewport: a fluid frame fills the pane less the scrollbar’s gutters, a fixed one leaves its gutter', () => { const pane = { width: 800, height: 600 }; const fluid = previewViewport(undefined, pane, undefined); - assert.deepEqual(fluid, { width: 800, height: 600, scale: 1 }); + assert.deepEqual(fluid, { width: 782, height: 600, scale: 1 }); + assert.equal(fluidFrameWidthPx(800), 782); + assert.equal(fluidFrameWidthPx(10), 0); + assert.equal(fluidFrameWidthPx(0), 0); + assert.equal(previewViewport(undefined, { width: 10, height: 600 }, undefined).width, 1, 'a frame keeps at least a pixel'); const fixed = previewViewport(1440, pane, undefined); assert.equal(fixed.scale, (800 - 24) / 1440); assert.equal(Math.round(fixed.height * fixed.scale), 600 - 32); diff --git a/test/renderer/preview/desktopDeviceChromium.test.js b/test/renderer/preview/desktopDeviceChromium.test.js index a124aca06..299881413 100644 --- a/test/renderer/preview/desktopDeviceChromium.test.js +++ b/test/renderer/preview/desktopDeviceChromium.test.js @@ -1,5 +1,5 @@ -// Goal: in the browser Desktop ships, the Desktop device in a narrow pane draws the page at the pane's own width, -// never scaled or shrunk: an 882px pane lays the page out at 882px, so its `(width < 64rem)` rules (Laptop's) +// Goal: in the browser Desktop ships, the Desktop device in a narrow pane draws the page at the pane's own width less +// the scrollbar's two 9px gutters, never scaled or shrunk: an 882px pane lays the page out at 864px, so its `(width < 64rem)` rules (Laptop's) // apply, as in a browser window that size, and the toolbar says Laptop rather than Desktop. Switching devices // never draws a frame of the page at a width other than the old or the new device's (no flicker through the pane // width). @@ -21,8 +21,10 @@ const { buildSync } = require('esbuild'); const { repoPath } = require('../../helpers/sources.js'); const PANE = { width: 882, height: 700 }; +// The fluid frame leaves a 9px gutter on each side for the canvas's scrollbar (previewViewport.ts `FLUID_GUTTER_PX`). +const FLUID_PAGE_WIDTH_PX = PANE.width - 18; const SWITCHES = ['laptop', 'desktop', 'tablet', 'desktop', 'phone', 'desktop']; -const DEVICE_WIDTH_PX = { laptop: 1023, tablet: 767, phone: 479, desktop: PANE.width }; +const DEVICE_WIDTH_PX = { laptop: 1023, tablet: 767, phone: 479, desktop: FLUID_PAGE_WIDTH_PX }; // The import paths are JSON-quoted: a Windows path's `\` inside a plain quoted string is an // escape, so a quoted literal only works on POSIX. @@ -135,9 +137,9 @@ function check(output) { if (before === undefined || after === undefined) { return ['both modes were read']; } - // The fluid all-breakpoints frame and Desktop both fill the 882px pane, and so agree. - if (before.innerWidth !== PANE.width) { - failures.push(`before: the filling page is the pane's width (${before.innerWidth})`); + // The fluid all-breakpoints frame and Desktop both fill the 882px pane less its gutters, and so agree. + if (before.innerWidth !== FLUID_PAGE_WIDTH_PX) { + failures.push(`before: the filling page is the pane's width less its gutters (${before.innerWidth})`); } if (before.laptop !== true) { failures.push('before: the filling page matches (width < 64rem)'); @@ -151,8 +153,8 @@ function check(output) { if (after.laptop !== true) { failures.push("after: window.matchMedia('(width < 64rem)').matches is true inside the frame, as in an 882px window"); } - if (after.innerWidth !== PANE.width) { - failures.push(`after: the page is laid out at the pane's width (${after.innerWidth})`); + if (after.innerWidth !== FLUID_PAGE_WIDTH_PX) { + failures.push(`after: the page is laid out at the pane's width less its gutters (${after.innerWidth})`); } if (after.background !== 'rgb(255, 0, 0)') { failures.push(`after: the Laptop rule paints the page (${after.background})`); diff --git a/test/renderer/preview/panelDragHold.test.js b/test/renderer/preview/panelDragHold.test.js index cee9a4c36..10df98a35 100644 --- a/test/renderer/preview/panelDragHold.test.js +++ b/test/renderer/preview/panelDragHold.test.js @@ -43,8 +43,9 @@ buildSync({ const hold = require(output); test('the viewport follows the space it has, growing and shrinking', () => { - assert.deepEqual(hold.previewViewport(undefined, { width: 500, height: 600 }, undefined), { width: 500, height: 600, scale: 1 }); - assert.deepEqual(hold.previewViewport(undefined, { width: 1400, height: 600 }, undefined), { width: 1400, height: 600, scale: 1 }); + // A fluid frame keeps 9px each side for the canvas's scrollbar (previewViewport.ts): 18px less than its container. + assert.deepEqual(hold.previewViewport(undefined, { width: 500, height: 600 }, undefined), { width: 482, height: 600, scale: 1 }); + assert.deepEqual(hold.previewViewport(undefined, { width: 1400, height: 600 }, undefined), { width: 1382, height: 600, scale: 1 }); const fixed = hold.previewViewport(768, { width: 400, height: 600 }, undefined); assert.equal(fixed.width, 768); assert.equal(fixed.scale, (400 - 24) / 768); @@ -98,7 +99,7 @@ test('the canvas follows a panel drag live and renders the fluid frame once, on const root = createRoot(document.getElementById('root')); try { await act(() => root.render(React.createElement(Canvas))); - assert.equal(last().width, 2000); + assert.equal(last().width, 2000 - 18, 'the container less the scrollbar’s two gutters'); assert.equal(last().settling, false); await act(() => hold.setPanelDragPhase('dragging')); assert.equal(last().settling, true, 'The frame skips its width transition during the drag'); @@ -109,7 +110,7 @@ test('the canvas follows a panel drag live and renders the fluid frame once, on } assert.equal(renders.length, dragStart, 'A fluid frame follows by CSS: no preview render mid-drag'); await act(() => hold.setPanelDragPhase('idle')); - assert.equal(last().width, 2100, 'Release measures once, with the final width'); + assert.equal(last().width, 2100 - 18, 'Release measures once, with the final width'); // Counted among the release frames (settling): the transition's own end is a timer that a loaded // runner can fire inside this act, and it is one more render whatever the number of steps. const releaseRenders = renders.slice(dragStart).filter((render) => render.settling); @@ -120,7 +121,7 @@ test('the canvas follows a panel drag live and renders the fluid frame once, on ); assert.equal(last().settling, false, 'The transition returns the frame after release'); await resize(1700); - assert.equal(last().width, 1700, 'Without a drag the canvas follows its container'); + assert.equal(last().width, 1700 - 18, 'Without a drag the canvas follows its container'); // A fixed-width frame rescales at each step, both ways, because its scale is React state. device = 'tablet'; await act(() => root.render(React.createElement(Canvas))); diff --git a/test/renderer/preview/previewLifecycle.test.js b/test/renderer/preview/previewLifecycle.test.js index 84821624d..ef490b5dc 100644 --- a/test/renderer/preview/previewLifecycle.test.js +++ b/test/renderer/preview/previewLifecycle.test.js @@ -693,14 +693,14 @@ test('custom widths preserve layout size, scale ' + 'to fit, and reset with devi await setWidth('7680'); assert.equal(sized.style.width, '7680px'); await act(() => document.querySelector('[data-tooltip="Reset canvas to available width"]').click()); - // An 824px pane: Desktop fills it at the pane's own width, never scaled, so the page's media queries see 824px. - assert.equal(sized.style.width, '100%'); + // An 824px pane: Desktop fills it less the scrollbar's two 9px gutters, never scaled, so the page's media queries see 806px. + assert.equal(sized.style.width, 'calc(100% - 18px)'); assert.equal(sized.style.height, '100%'); assert.doesNotMatch(sized.style.transform, /scale/); containerWidth = 2000; await act(() => observers.forEach((callback) => callback())); // A wider pane: the fluid frame fills the canvas by CSS too, so it follows a side-panel drag without a render. - assert.equal(sized.style.width, '100%'); + assert.equal(sized.style.width, 'calc(100% - 18px)'); assert.equal(sized.style.height, '100%'); assert.doesNotMatch(sized.style.transform, /scale/); assert.equal(document.querySelector('iframe'), frame); diff --git a/test/renderer/preview/resizeHandlesModes.test.js b/test/renderer/preview/resizeHandlesModes.test.js index 8dbc4077d..f212194f6 100644 --- a/test/renderer/preview/resizeHandlesModes.test.js +++ b/test/renderer/preview/resizeHandlesModes.test.js @@ -46,7 +46,7 @@ const settle = () => new Promise((resolve) => setTimeout(resolve, 20)); test('AppShell draws the preview mode through the shared stage and the window size state', () => { const shell = fs.readFileSync(repoPath('src/app/shell/AppShell.tsx'), 'utf8'); - assert.match(shell, //); + assert.match(shell, //); assert.match(shell, /usePreviewSizing\(app\.device, app\.previewDimensions, breakpoints, \{ deviceShortcuts: false \}, app\.setDevice\)/); const panes = fs.readFileSync(repoPath('src/app/shell/AppPanes.tsx'), 'utf8'); assert.match(panes, /dimensions=\{app\.previewDimensions\}/); diff --git a/test/renderer/style/codeChips.test.js b/test/renderer/style/codeChips.test.js index d2782d261..6778481c8 100644 --- a/test/renderer/style/codeChips.test.js +++ b/test/renderer/style/codeChips.test.js @@ -675,6 +675,7 @@ test('the saved preference is read once from the desktop bridge, and a failure k aiTrackChanges: true, aiReviewChanges: false, codeChips: false, + canvasScrollbar: 'off', }; }, }; diff --git a/test/shared/ipc/preferences.test.ts b/test/shared/ipc/preferences.test.ts index 3146bd904..b4c08a874 100644 --- a/test/shared/ipc/preferences.test.ts +++ b/test/shared/ipc/preferences.test.ts @@ -1,12 +1,13 @@ -// Verify preference replies before the desktop settings popup consumes them. -// Valid values round-trip; missing and malformed boolean fields are rejected. +// Verify preference replies before the desktop settings popup consumes them, and the changes it sends. +// Valid values round-trip; missing and malformed fields are rejected; the canvas scrollbar's breakpoint id is read +// into its typed form, and a change's parsed output parses again unchanged (the renderer sends what it parsed). import assert from 'node:assert/strict'; import test from 'node:test'; -import { parsePreferenceName, parsePreferences, parsePreferenceResult } from '#dist/shared/ipc/preferences.js'; +import { parsePreferenceChange, parsePreferenceName, parsePreferences, parsePreferenceResult } from '#dist/shared/ipc/preferences.js'; test('desktop preference replies require boolean values and save status', () => { // Main always sends every preference, appsPersonHidden included (electron/main.ts), so none is optional here. - const preferences = { + const switches = { sound: true, usageCountsEnabled: false, appsPersonHidden: true, @@ -15,11 +16,17 @@ test('desktop preference replies require boolean values and save status', () => aiReviewChanges: false, codeChips: true, }; - assert.deepEqual(parsePreferences(preferences), preferences); + const preferences = { ...switches, canvasScrollbar: 'laptop' }; + const parsed = { ...switches, canvasScrollbar: { kind: 'from', breakpointId: 'laptop' } }; + assert.deepEqual(parsePreferences(preferences), parsed); + assert.deepEqual(parsePreferences({ ...preferences, canvasScrollbar: 'off' }).canvasScrollbar, { kind: 'off' }); assert.deepEqual(parsePreferenceResult({ ...preferences, saved: true }), { - ...preferences, + ...parsed, saved: true, }); + for (const canvasScrollbar of [undefined, '', 'Laptop', true, 3]) { + assert.throws(() => parsePreferences({ ...preferences, canvasScrollbar })); + } for (const value of [ undefined, {}, @@ -50,3 +57,28 @@ test('a preference change names a known preference', () => { assert.throws(() => parsePreferenceName(name), /Unknown preference/); } }); + +test('a preference change is a switch flipped or the canvas scrollbar breakpoint, and parses again unchanged', () => { + const flip = parsePreferenceChange({ setting: 'codeChips', enabled: false }); + assert.deepEqual(flip, { setting: 'codeChips', enabled: false }); + assert.deepEqual(parsePreferenceChange(flip), flip); + for (const value of ['off', 'laptop', 'bp-12']) { + const pick = parsePreferenceChange({ setting: 'canvasScrollbar', value }); + assert.deepEqual(pick, { setting: 'canvasScrollbar', value }); + assert.deepEqual(parsePreferenceChange(pick), pick); + } + for (const input of [ + undefined, + 'canvasScrollbar', + { setting: 'canvasScrollbar' }, + { setting: 'canvasScrollbar', value: '' }, + { setting: 'canvasScrollbar', value: 'Laptop' }, + { setting: 'canvasScrollbar', value: 'x'.repeat(25) }, + { setting: 'canvasScrollbar', enabled: true }, + { setting: 'codeChips', value: 'laptop' }, + { setting: 'codeChips', enabled: 'no' }, + { setting: 'unknown', enabled: true }, + ]) { + assert.throws(() => parsePreferenceChange(input), Error, JSON.stringify(input)); + } +}); diff --git a/test/shared/properties/canvasScrollbar.test.ts b/test/shared/properties/canvasScrollbar.test.ts new file mode 100644 index 000000000..78cb75d85 --- /dev/null +++ b/test/shared/properties/canvasScrollbar.test.ts @@ -0,0 +1,174 @@ +// Goal: the canvas scrollbar contract (shared/properties/canvasScrollbar.ts) accepts exactly what the app, the frame +// and the settings file mean, and nothing that could escape it: a preference is `off` or a breakpoint id, a width is a +// whole canvas width inside the breakpoint bounds, a scroll report is finite and bounded, and the thumb stays on its +// track whatever the page's size. +// Method: each parser takes known-good input and every known-bad shape, including values just past each bound; the +// builders' output parses back; the stylesheet and query text are pinned; the thumb math is checked at the edges and +// read backwards; violated preconditions throw with their message pinned. +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { CANVAS_SCROLLBAR_DEFAULT, canvasScrollbarPreferenceText, parseCanvasScrollbarPreference } from '#dist/shared/properties/canvasScrollbarChoice.js'; +import { + CANVAS_SCROLLBAR_LIMITS, + canvasScrollbarCss, + canvasScrollbarMessage, + chromiumScrollbarBreakpoints, + chromiumScrollbarFromPx, + chromiumScrollbarQuery, + pageScrollMessage, + pageScrollToMessage, + parseCanvasScrollbarMessage, + parsePageScrollMessage, + parsePageScrollToMessage, + scrollThumb, + scrollTopForThumb, +} from '#dist/shared/properties/canvasScrollbar.js'; +import { BREAKPOINT_DEFAULT_LIST, resolveBreakpoints } from '#dist/shared/properties/projectBreakpoints.js'; + +const SCROLL = { topPx: 0, heightPx: 4000, viewHeightPx: 800, chromium: false }; +// A null as it reaches a boundary: out of a parsed message, never written in our own code. +const NULL_FROM_JSON: unknown = JSON.parse('null'); + +test('the preference is off or a breakpoint id, and its stored text reads back', () => { + assert.deepEqual(parseCanvasScrollbarPreference('off'), { kind: 'off' }); + assert.deepEqual(parseCanvasScrollbarPreference('laptop'), { kind: 'from', breakpointId: 'laptop' }); + assert.deepEqual(parseCanvasScrollbarPreference('bp-12'), { kind: 'from', breakpointId: 'bp-12' }); + assert.deepEqual(CANVAS_SCROLLBAR_DEFAULT, { kind: 'off' }); + for (const stored of ['off', 'laptop', 'bp-12', 'a'.repeat(24)]) { + assert.equal(canvasScrollbarPreferenceText(parseCanvasScrollbarPreference(stored)), stored); + } + for (const bad of [undefined, NULL_FROM_JSON, true, 3, {}, '', 'Laptop', '3bp', '-x', 'bp_1', 'laptop;', 'laptop ', 'a'.repeat(25)]) { + assert.throws(() => parseCanvasScrollbarPreference(bad), /canvasScrollbar/, JSON.stringify(bad)); + } +}); + +test('a computer breakpoint and every wider frame keep Chromium from that breakpoint’s canvas width', () => { + const breakpoints = resolveBreakpoints(BREAKPOINT_DEFAULT_LIST); + assert.equal(chromiumScrollbarFromPx({ kind: 'off' }, breakpoints), undefined); + assert.equal(chromiumScrollbarFromPx({ kind: 'from', breakpointId: 'laptop' }, breakpoints), 1023); // width < 64rem + // A tablet or a phone floats its bar over the page: never offered, and a saved one acts as Off. + assert.equal(chromiumScrollbarFromPx({ kind: 'from', breakpointId: 'tablet' }, breakpoints), undefined); + assert.equal(chromiumScrollbarFromPx({ kind: 'from', breakpointId: 'phone' }, breakpoints), undefined); + // A breakpoint this project does not have: the canvas's bar everywhere, as Off. + assert.equal(chromiumScrollbarFromPx({ kind: 'from', breakpointId: 'bp-9' }, breakpoints), undefined); + assert.equal(chromiumScrollbarFromPx({ kind: 'from', breakpointId: 'laptop' }, []), undefined); +}); + +test('Desktop and every wider frame keep Chromium from one pixel past the widest narrower breakpoint, whatever the list', () => { + const desktop = parseCanvasScrollbarPreference('desktop'); + assert.deepEqual(desktop, { kind: 'from', breakpointId: 'desktop' }); + assert.equal(canvasScrollbarPreferenceText(desktop), 'desktop'); + // The default list: Laptop is `width < 64rem` (up to 1023), so Desktop starts at 1024, past Laptop's own 1023. + assert.equal(chromiumScrollbarFromPx(desktop, resolveBreakpoints(BREAKPOINT_DEFAULT_LIST)), 1024); + // A wider (`up`) breakpoint never moves where Desktop starts; the narrower ones do, whatever their number and names. + const large = { id: 'bp-1', name: 'Large', direction: 'up' as const, setting: { value: 160, unit: 'rem' as const } }; + const small = { id: 'bp-2', name: 'Small laptop', direction: 'down' as const, setting: { value: 1200, unit: 'px' as const } }; + assert.equal(chromiumScrollbarFromPx(desktop, resolveBreakpoints([large, ...BREAKPOINT_DEFAULT_LIST])), 1024); + assert.equal(chromiumScrollbarFromPx(desktop, resolveBreakpoints([large, small, ...BREAKPOINT_DEFAULT_LIST])), 1200); + assert.equal(chromiumScrollbarFromPx({ kind: 'from', breakpointId: 'bp-1' }, resolveBreakpoints([large, ...BREAKPOINT_DEFAULT_LIST])), 2560); + // The choices, widest first, whatever the list: every wider breakpoint and the computer-sized narrower ones, by + // position and width, never by name; a narrower one in a tablet's or a phone's range is left out. + const tabletSized = { id: 'bp-3', name: 'Big tablet', direction: 'down' as const, setting: { value: 860, unit: 'px' as const } }; + // In list order, strictly decreasing: 2560, 1200, 1024 (Laptop), 860, 768 (Tablet), 480 (Phone). + const [laptop, tablet, phone] = BREAKPOINT_DEFAULT_LIST; + assert.ok(laptop !== undefined && tablet !== undefined && phone !== undefined); + const list = resolveBreakpoints([large, small, laptop, tabletSized, tablet, phone]); + assert.deepEqual( + chromiumScrollbarBreakpoints(list).map((breakpoint) => breakpoint.id), + ['bp-1', 'bp-2', 'laptop'], + ); + assert.equal(chromiumScrollbarFromPx({ kind: 'from', breakpointId: 'bp-2' }, list), 1199); + assert.equal(chromiumScrollbarFromPx({ kind: 'from', breakpointId: 'bp-3' }, list), undefined); + assert.deepEqual(chromiumScrollbarBreakpoints([]), []); + // No narrower breakpoint: every frame below the wider ones is Desktop, so every frame keeps Chromium's bar. + assert.equal(chromiumScrollbarFromPx(desktop, resolveBreakpoints([large])), 280); + assert.equal(chromiumScrollbarFromPx(desktop, []), 280); +}); + +test('the app’s word to the frame carries a bounded canvas width or none', () => { + assert.deepEqual(canvasScrollbarMessage(undefined), { type: 'avb:canvas-scrollbar' }); + assert.deepEqual(canvasScrollbarMessage(1023), { type: 'avb:canvas-scrollbar', chromiumFromPx: 1023 }); + for (const good of [280, 1023, 7681]) { + assert.deepEqual(parseCanvasScrollbarMessage({ type: 'avb:canvas-scrollbar', chromiumFromPx: good }), { + type: 'avb:canvas-scrollbar', + chromiumFromPx: good, + }); + } + for (const bad of [ + undefined, + 'avb:canvas-scrollbar', + { type: 'avb:other', chromiumFromPx: 1023 }, + { type: 'avb:canvas-scrollbar', chromiumFromPx: '1023' }, + { type: 'avb:canvas-scrollbar', chromiumFromPx: 1023.5 }, + { type: 'avb:canvas-scrollbar', chromiumFromPx: 279 }, + { type: 'avb:canvas-scrollbar', chromiumFromPx: 7682 }, + { type: 'avb:canvas-scrollbar', chromiumFromPx: Number.NaN }, + { type: 'avb:canvas-scrollbar', chromiumFromPx: NULL_FROM_JSON }, + ]) { + assert.equal(parseCanvasScrollbarMessage(bad), undefined, JSON.stringify(bad)); + } + assert.throws(() => canvasScrollbarMessage(12), /Assertion failed: canvasScrollbarMessage: the message parses/); +}); + +test('the frame’s stylesheet hides the root bar everywhere or below the width, and the query names the rest', () => { + assert.equal(canvasScrollbarCss(undefined), 'html { scrollbar-width: none !important; }'); + assert.equal(canvasScrollbarCss(1023), '@media (width < 1023px) { html { scrollbar-width: none !important; } }'); + assert.equal(chromiumScrollbarQuery(undefined), undefined); + assert.equal(chromiumScrollbarQuery(1023), '(width >= 1023px)'); + assert.throws(() => canvasScrollbarCss(12), /Assertion failed: canvasScrollbarCss: a canvas width within the breakpoint bounds/); + assert.throws(() => chromiumScrollbarQuery(1023.5), /Assertion failed: chromiumScrollbarQuery: a canvas width within the breakpoint bounds/); +}); + +test('the frame’s scroll report is finite, never negative and bounded', () => { + assert.deepEqual(pageScrollMessage(SCROLL), { type: 'avb:page-scroll', ...SCROLL }); + assert.deepEqual(parsePageScrollMessage({ type: 'avb:page-scroll', ...SCROLL, chromium: true }), { type: 'avb:page-scroll', ...SCROLL, chromium: true }); + const max = CANVAS_SCROLLBAR_LIMITS.pagePxMax; + assert.equal(parsePageScrollMessage({ type: 'avb:page-scroll', ...SCROLL, heightPx: max })?.heightPx, max); + for (const bad of [ + undefined, + { ...SCROLL }, + { type: 'avb:page-scroll', ...SCROLL, topPx: -1 }, + { type: 'avb:page-scroll', ...SCROLL, heightPx: max + 1 }, + { type: 'avb:page-scroll', ...SCROLL, viewHeightPx: Number.POSITIVE_INFINITY }, + { type: 'avb:page-scroll', ...SCROLL, topPx: Number.NaN }, + { type: 'avb:page-scroll', ...SCROLL, topPx: '0' }, + { type: 'avb:page-scroll', ...SCROLL, chromium: 'no' }, + { type: 'avb:page-scroll', topPx: 0, heightPx: 10, chromium: false }, + ]) { + assert.equal(parsePageScrollMessage(bad), undefined, JSON.stringify(bad)); + } + assert.deepEqual(pageScrollToMessage(120), { type: 'avb:page-scroll-to', topPx: 120 }); + assert.deepEqual(parsePageScrollToMessage({ type: 'avb:page-scroll-to', topPx: 0 }), { type: 'avb:page-scroll-to', topPx: 0 }); + for (const bad of [ + { type: 'avb:page-scroll-to' }, + { type: 'avb:page-scroll-to', topPx: -5 }, + { type: 'avb:page-scroll-to', topPx: max + 1 }, + { type: 'avb:scroll-to', topPx: 5 }, + ]) { + assert.equal(parsePageScrollToMessage(bad), undefined, JSON.stringify(bad)); + } + assert.throws(() => pageScrollToMessage(-1), /Assertion failed: pageScrollToMessage: the message parses/); +}); + +test('the thumb is the visible share of its track, stays on it, and reads back to the page scroll', () => { + // 800 of 4000 visible on an 800px track: a 160px thumb with 640px to travel over 3200px of page. + assert.deepEqual(scrollThumb(SCROLL, 800, 24), { offsetPx: 0, lengthPx: 160 }); + assert.deepEqual(scrollThumb({ ...SCROLL, topPx: 1600 }, 800, 24), { offsetPx: 320, lengthPx: 160 }); + assert.deepEqual(scrollThumb({ ...SCROLL, topPx: 3200 }, 800, 24), { offsetPx: 640, lengthPx: 160 }); + // Scrolled past either end (an overscroll, a stale report): the thumb stays on its track. + assert.deepEqual(scrollThumb({ ...SCROLL, topPx: 9000 }, 800, 24), { offsetPx: 640, lengthPx: 160 }); + // A page with nothing to scroll has no thumb. + assert.equal(scrollThumb({ topPx: 0, heightPx: 800, viewHeightPx: 800 }, 800, 24), undefined); + assert.equal(scrollThumb({ topPx: 0, heightPx: 600, viewHeightPx: 800 }, 800, 24), undefined); + // A very long page keeps a thumb a pointer can catch, and its travel still spans the page. + const long = { topPx: 0, heightPx: 1_000_000, viewHeightPx: 800 }; + assert.equal(scrollThumb(long, 800, 24)?.lengthPx, 24); + assert.equal(scrollTopForThumb(long, 800, 24, 776), 999_200); + // Read backwards, clamped to the page. + assert.equal(scrollTopForThumb(SCROLL, 800, 24, 320), 1600); + assert.equal(scrollTopForThumb(SCROLL, 800, 24, -50), 0); + assert.equal(scrollTopForThumb(SCROLL, 800, 24, 5000), 3200); + assert.equal(scrollTopForThumb({ heightPx: 800, viewHeightPx: 800 }, 800, 24, 100), 0); + assert.throws(() => scrollThumb(SCROLL, -1, 24), /Assertion failed: scrollThumb: a track has a length/); + assert.throws(() => scrollThumb(SCROLL, 800, -1), /Assertion failed: scrollThumb: a thumb has a length/); +}); From b5ec1ffc2ad14f3860346799d68773a9517ca9ee Mon Sep 17 00:00:00 2001 From: SylvainDruaux Date: Mon, 23 Nov 2026 21:54:05 +0100 Subject: [PATCH 2/3] test(preview): the capture check allows a display's colour shift On a Retina Mac, capturePage returns the magenta toolbar (#ff00ff) as 255, 3, 255: the display's colour conversion moves green by 3, past the check's 2-unit tolerance, so the whole-window capture read as having no toolbar and every scenario failed locally. The toolbar is now recognised as clearly magenta (red and blue high, green low), which no such conversion turns into the white stage or an outline colour. --- .../preview/canvasCaptureOutlinesChromium.test.js | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/test/renderer/preview/canvasCaptureOutlinesChromium.test.js b/test/renderer/preview/canvasCaptureOutlinesChromium.test.js index 8128b327d..288ecdffb 100644 --- a/test/renderer/preview/canvasCaptureOutlinesChromium.test.js +++ b/test/renderer/preview/canvasCaptureOutlinesChromium.test.js @@ -66,6 +66,17 @@ function count(image, [red, green, blue]) { } return matches; } +// Pixels of the toolbar: clearly magenta, red and blue high and green low. A display's colour conversion moves a channel by a +// few units (a Retina Mac captures #ff00ff as 255, 3, 255), past count()'s step, but never far enough to read as the white +// stage or an outline colour. +function countMagenta(image) { + const bitmap = image.toBitmap(); + let matches = 0; + for (let at = 0; at + 3 < bitmap.length; at += 4) { + if (bitmap[at] >= 200 && bitmap[at + 1] <= 60 && bitmap[at + 2] >= 200) { matches += 1; } + } + return matches; +} app.whenReady().then(async () => { const server = http.createServer((request, response) => { const name = request.url.split('?')[0] === '/' ? 'host.html' : request.url.split('?')[0].slice(1); @@ -93,7 +104,7 @@ app.whenReady().then(async () => { const stage = await win.webContents.capturePage(STAGE); const whole = await win.webContents.capturePage(); const size = stage.getSize(); - const result = { size, colours, magentaInStage: count(stage, [255, 0, 255]), magentaInWindow: count(whole, [255, 0, 255]) }; + const result = { size, colours, magentaInStage: countMagenta(stage), magentaInWindow: countMagenta(whole) }; if (colours.outline) { result.outlinePixels = count(stage, colours.outline); } if (colours.tag) { result.tagPixels = count(stage, colours.tag); } output.scenarios[scenario] = result; From fa4c969d3640da3c681d3f932d8be1d77e7b7181 Mon Sep 17 00:00:00 2001 From: SylvainDruaux Date: Tue, 24 Nov 2026 10:33:57 +0100 Subject: [PATCH 3/3] fix(preview): Desktop's outlines and guides sit on the page again The fluid Desktop frame leaves a 9px gutter on each side for the canvas's scrollbar, but the overlay layer above it (outlines, column guides, drop indicators) kept the pane's full width. Both are centred, so every overlay drew 9px left of the page and 18px too wide. The frame and its overlay layer now take one width, FLUID_FRAME_WIDTH, in the app and in Studio, and a test pins that the layer covers exactly the fluid frame. --- src/features/preview/PreviewPane.tsx | 3 ++- src/features/preview/SizedFrame.tsx | 4 ++-- src/features/preview/previewViewport.ts | 3 +++ studio/src/features/preview/PreviewCanvas.tsx | 3 ++- test/renderer/preview/previewLifecycle.test.js | 2 ++ 5 files changed, 11 insertions(+), 4 deletions(-) diff --git a/src/features/preview/PreviewPane.tsx b/src/features/preview/PreviewPane.tsx index e0f9e4b42..7beb42fbb 100644 --- a/src/features/preview/PreviewPane.tsx +++ b/src/features/preview/PreviewPane.tsx @@ -23,6 +23,7 @@ import { useProjectBreakpoints } from '../../ipc/useProjectBreakpoints'; import { usePreviewRuntime, type CanvasSelectInfo, type JudgeCanvasEvent, type PreviewRuntimeProps } from './previewRuntime'; import type { CanvasNoticeEvent } from './canvasClickRetry'; import type { PreviewReloadReason } from './previewMessages'; +import { FLUID_FRAME_WIDTH } from './previewViewport'; import './previewViewport.css'; import type { LiveValue } from '../../ui/liveValue'; import { GuideOverlay } from './GuideOverlay'; @@ -264,7 +265,7 @@ function DesignPreview({ style={ width ? { width: sizing.viewport.width * scale, height: sizing.viewport.height * scale, borderRadius: 10 * scale } - : { width: '100%', height: '100%', borderRadius: 0 } + : { width: FLUID_FRAME_WIDTH, height: '100%', borderRadius: 0 } } > {/* First in the layer, so the outlines and spacing bands paint over it. */} diff --git a/src/features/preview/SizedFrame.tsx b/src/features/preview/SizedFrame.tsx index 727c2e506..4aca7ad61 100644 --- a/src/features/preview/SizedFrame.tsx +++ b/src/features/preview/SizedFrame.tsx @@ -14,7 +14,7 @@ import type { ReactNode } from 'react'; import { assert } from '../../../shared/core/assert'; import type { PreviewSizing } from './usePreviewSizing'; import { CanvasScrollbar } from './CanvasScrollbar'; -import { FLUID_GUTTER_PX } from './previewViewport'; +import { FLUID_FRAME_WIDTH } from './previewViewport'; import './previewViewport.css'; export interface SizedFrameProps { @@ -41,7 +41,7 @@ export function SizedFrame({ sizing, chromiumFromPx, children }: SizedFrameProps // without a render (usePreviewSizing puts off its measure until release). style={ sizing.width === undefined - ? { width: `calc(100% - ${FLUID_GUTTER_PX.side}px)`, height: '100%', bottom: 'auto', transform: 'translateX(-50%)' } + ? { width: FLUID_FRAME_WIDTH, height: '100%', bottom: 'auto', transform: 'translateX(-50%)' } : { width: sizing.viewport.width, height: sizing.viewport.height, bottom: 'auto', transform: `translateX(-50%) scale(${scale})` } } > diff --git a/src/features/preview/previewViewport.ts b/src/features/preview/previewViewport.ts index a532c4ea2..697cadaff 100644 --- a/src/features/preview/previewViewport.ts +++ b/src/features/preview/previewViewport.ts @@ -20,6 +20,9 @@ export function parsePreviewWidth(input: string): number | undefined { const FRAMED_GUTTER_PX = { side: 24, vertical: 32 } as const; export const FLUID_GUTTER_PX = { side: 18 } as const; +/** A fluid frame's CSS width, and its overlay layer's: both centred, so the outlines and guides sit exactly on the page. */ +export const FLUID_FRAME_WIDTH = `calc(100% - ${FLUID_GUTTER_PX.side}px)`; + /** The width a fluid frame draws the page at in a pane this wide: the pane less its gutters, 0 for an unmeasured pane. */ export function fluidFrameWidthPx(paneWidthPx: number): number { assert(Number.isFinite(paneWidthPx), 'fluidFrameWidthPx: the pane width is finite'); diff --git a/studio/src/features/preview/PreviewCanvas.tsx b/studio/src/features/preview/PreviewCanvas.tsx index 3a12383bc..e1217c0fa 100644 --- a/studio/src/features/preview/PreviewCanvas.tsx +++ b/studio/src/features/preview/PreviewCanvas.tsx @@ -25,6 +25,7 @@ import CanvasView from '../../../vendor/stacki/src/features/preview/CanvasView'; import { useProjectBreakpoints } from '../../../vendor/stacki/src/ipc/useProjectBreakpoints'; import { usePreviewSizing } from '../../../vendor/stacki/src/features/preview/usePreviewSizing'; import type { usePreviewDimensions } from '../../../vendor/stacki/src/features/preview/usePreviewSizing'; +import { FLUID_FRAME_WIDTH } from '../../../vendor/stacki/src/features/preview/previewViewport'; import '../../../vendor/stacki/src/features/preview/previewViewport.css'; import { SizedFrame } from '../../../vendor/stacki/src/features/preview/SizedFrame'; import { CollectionEditor } from '../collections/CollectionEditor'; @@ -253,7 +254,7 @@ function CanvasOverlays({ height: sizing.viewport.height * sizing.viewport.scale, borderRadius: 10 * sizing.viewport.scale, } - : { width: '100%', height: '100%', borderRadius: 0 }; + : { width: FLUID_FRAME_WIDTH, height: '100%', borderRadius: 0 }; // The overlays are drawn in the page's own coordinates over the user's site, which never mirrors, so they stay left to right. return (
diff --git a/test/renderer/preview/previewLifecycle.test.js b/test/renderer/preview/previewLifecycle.test.js index ef490b5dc..427cc8ecd 100644 --- a/test/renderer/preview/previewLifecycle.test.js +++ b/test/renderer/preview/previewLifecycle.test.js @@ -697,6 +697,8 @@ test('custom widths preserve layout size, scale ' + 'to fit, and reset with devi assert.equal(sized.style.width, 'calc(100% - 18px)'); assert.equal(sized.style.height, '100%'); assert.doesNotMatch(sized.style.transform, /scale/); + // The outlines and the column guides are drawn in their own layer, centred like the frame: same width, or they slide off the page. + assert.equal(document.querySelector('.preview-overlay-layer').style.width, sized.style.width, 'the overlay layer covers exactly the fluid frame'); containerWidth = 2000; await act(() => observers.forEach((callback) => callback())); // A wider pane: the fluid frame fills the canvas by CSS too, so it follows a side-panel drag without a render.