Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions docs/contracts.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
5 changes: 5 additions & 0 deletions electron/app/mainValidation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -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;
}
Expand All @@ -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) {
Expand All @@ -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 }),
Expand Down
12 changes: 11 additions & 1 deletion electron/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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 };
Expand Down Expand Up @@ -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 };
Expand Down
4 changes: 4 additions & 0 deletions electron/preload/frameQueries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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;
Expand Down
197 changes: 197 additions & 0 deletions electron/preload/frameScrollbar.ts
Original file line number Diff line number Diff line change
@@ -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
// <html> 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 <style> this module writes, last in <head> when made. A canvas patch keeps it: the patch only touches
// nodes the server rendered (morphPatch.ts), and a reload starts a new page that the app tells again.
function styleElement(): HTMLStyleElement | undefined {
const existing = document.getElementById(STYLE_ID);
if (existing instanceof HTMLStyleElement) {
return existing;
}
const parent = document.head ?? document.documentElement;
if (parent === null) {
return undefined;
}
const style = document.createElement('style');
style.id = STYLE_ID;
parent.appendChild(style);
return style;
}

function scheduleReport(): void {
if (reportScheduled) {
return;
}
reportScheduled = true;
requestAnimationFrame(report);
}

// One report per animation frame at most, and none when nothing the canvas draws has changed.
function report(): void {
reportScheduled = false;
const send = post;
if (send === undefined) {
return;
}
const scroll = pageScrollNow();
if (scroll === undefined) {
return; // No page yet: `readystatechange` and `load` bring the first report.
}
if (lastReport !== undefined && sameScroll(lastReport, scroll)) {
return;
}
lastReport = scroll;
send(pageScrollMessage(scroll));
}

function sameScroll(previous: PageScroll, next: PageScroll): boolean {
if (previous.topPx !== next.topPx) {
return false;
}
if (previous.heightPx !== next.heightPx) {
return false;
}
if (previous.viewHeightPx !== next.viewHeightPx) {
return false;
}
return previous.chromium === next.chromium;
}

// A page past the bound is reported at the bound: the thumb is then as short as it goes, never wrong in kind.
function clampPagePx(value: number): number {
if (Number.isFinite(value)) {
return Math.min(CANVAS_SCROLLBAR_LIMITS.pagePxMax, Math.max(0, value));
}
return 0;
}
4 changes: 4 additions & 0 deletions electron/preload/preload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import { listenForDesign, markFrameMode } from './frameDesign';
import { listenForQueries, startWhenReady } from './frameQueries';
import { rememberScrollAcrossRecovery } from './frameScrollMemory';
import { reportErrorOverlay } from './frameErrorOverlay';
import { installPageScrollReport } from './frameScrollbar';

// A Stacki app's frame (stacki-app:) is the app's own sandboxed document: it
// gets neither half. It talks to Stacki only through postMessage and the RPC.
Expand Down Expand Up @@ -50,6 +51,9 @@ if (location.protocol === 'stacki-app:') {
listenForDesign();
listenForQueries();
startWhenReady();
// The canvas draws the page's scrollbar beside the frame from these reports (frameScrollbar.ts). Last, so the
// canvas's own listeners are in place whatever happens here.
installPageScrollReport(post);
} else {
exposeBridge();
}
4 changes: 2 additions & 2 deletions shared/ipc/ipcPayloads.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ import { parseImageFormat, parseImagePath } from './assetConversion';
import { parseGitHubRepository } from './githubRepository';
import { parseCommitDiffRequest } from './gitCommitDiff';
import { parseCommitAvatarRequest } from './commitAvatars';
import { parsePreferenceName } from './preferences';
import { parsePreferenceChange } from './preferences';
import { parseStudioSource } from './studioSetup';
import { parseStudioRequestId } from './studioProgress';
import { parseUpdateAction } from './updateState';
Expand Down Expand Up @@ -776,7 +776,7 @@ export const IPC_PAYLOADS = {
'recents:remove': pathText,
'selection:copy': object({ ...project, keys: strings }),
'settings:get': nothing,
'settings:set': object({ setting: parsePreferenceName, enabled: boolean }),
'settings:set': parsePreferenceChange,
'shell:openExternal': pathText,
'src:readSymbol': object({ ...source, name: text }),
'src:readText': object({ ...relative }),
Expand Down
Loading
Loading