diff --git a/CHANGELOG.md b/CHANGELOG.md index 87b15b0..09b6ec6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,25 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [Unreleased] +### Added + +- **The favourite drawing tools bar can be moved.** Drag it by the grip on its left end to anywhere + on the charts; it stays there after a restart and keeps inside the charts when the window shrinks. + +### Changed + +- **Sync looks after itself and stays quiet.** Problems you cannot act on are retried by themselves + instead of stopping sync until you press Try again. The status bar shows a small cloud icon that + no longer flickers to "Syncing" on every check; words appear only when sync needs you, such as + confirming large deletions or reconnecting GitHub. + +### Fixed + +- The drawing rail's cursor, magnet, Stay in Drawing Mode, Lock and Hide settings are kept between + launches instead of resetting each time the app opens. +- The main window reopens at the size and position it was closed at, maximised or full screen if it + was. A window last left on a monitor that is no longer connected opens on the main screen. + ## [1.1.0] - 2026-11-06 ### Added diff --git a/electron/main.ts b/electron/main.ts index 24d8d10..0a615e0 100644 --- a/electron/main.ts +++ b/electron/main.ts @@ -18,6 +18,7 @@ import { loadAccounts, secretCipher } from './accounts'; import { SessionPool } from './session-pool'; import { handleTradingView } from './tradingview'; import { AppZoom } from './app-zoom'; +import { WindowBounds } from './window-bounds'; import { isZoomStep } from '../shared/zoom'; import { AutomationHost } from './automation-host'; import type { AutomationEvent, AutomationMethod } from '../shared/automation'; @@ -199,6 +200,8 @@ async function applySettings(): Promise { } const zoom = new AppZoom(path.join(app.getPath('userData'), 'zoom.json'), (factor) => send('zoom', factor)); +const windowBounds = new WindowBounds(path.join(app.getPath('userData'), 'window.json')); +const minimumSize = { width: 960, height: 600 }; // Charts popped out of the layout: windows the renderer opens on about:blank and draws into itself. const popoutPrefix = 'openterm-pip-'; @@ -226,11 +229,13 @@ function closePopouts(): void { function createWindow(): void { isSyncFlushed = false; + const workAreas = [screen.getPrimaryDisplay(), ...screen.getAllDisplays()].map((display) => display.workArea); window = new BrowserWindow({ width: 1440, height: 900, - minWidth: 960, - minHeight: 600, + ...windowBounds.options(workAreas, minimumSize), + minWidth: minimumSize.width, + minHeight: minimumSize.height, title: 'OpenTerm5', show: false, // macOS takes the icon from the app bundle; Linux and Windows need it on the window. @@ -245,6 +250,7 @@ function createWindow(): void { nodeIntegration: false, }, }); + windowBounds.track(window); window.once('ready-to-show', () => window?.show()); window.on('focus', () => sync?.setFocused(true)); window.on('blur', () => sync?.setFocused(false)); @@ -628,6 +634,7 @@ if (!app.requestSingleInstanceLock()) { installMenu(); settings = await loadSettings(); await zoom.load(); + await windowBounds.load(); await device.load(); try { accounts = await loadAccounts(() => sync?.noteLocalChange()); } catch { journal('Saved accounts could not be loaded. Log in manually.', 'Accounts'); } diff --git a/electron/sync-service.test.ts b/electron/sync-service.test.ts index 4f3c53e..d739448 100644 --- a/electron/sync-service.test.ts +++ b/electron/sync-service.test.ts @@ -196,6 +196,29 @@ test('being offline retries later instead of stopping', async () => { assert.equal(first.view().status, 'idle'); }); +test('an unexpected failure retries quietly, is journalled once and clears on its own', async () => { + const github = fakeGitHub(); + const chart = new MemorySource('chart'); + const { first } = await setUpFirst(github, null, [chart]); + const snapshot = chart.snapshot.bind(chart); + let failures = 2; + chart.snapshot = async () => { + if (failures-- > 0) throw new Error('disk busy'); + return snapshot(); + }; + await first.service.handle('sync.syncNow', {}); + await first.tick(); + assert.equal(first.view().status, 'retrying'); + assert.equal(first.view().attention, null); + assert.ok(first.view().nextRunAt); + await first.tick(30_000); + assert.equal(first.view().status, 'retrying'); + assert.equal(first.journal.filter((line) => line.includes('disk busy')).length, 1); + await first.tick(60_000); + assert.equal(first.view().status, 'idle'); + assert.equal(first.view().error, null); +}); + test('an altered manifest stops sync and says why', async () => { const github = fakeGitHub(); const { first } = await setUpFirst(github); diff --git a/electron/sync-service.ts b/electron/sync-service.ts index 76a2b0d..19e22ff 100644 --- a/electron/sync-service.ts +++ b/electron/sync-service.ts @@ -820,7 +820,7 @@ export class SyncService { } private failed(error: Error): RunResult { - if (error instanceof SyncIntegrityError) return this.attend(error.reason, error.message); + if (error instanceof SyncIntegrityError) return error.reason === 'tooNew' ? this.retryQuietly(error.message) : this.attend(error.reason, error.message); if (error instanceof SyncSourceUnavailableError) { [this.status, this.error] = ['loading', error.message]; return { kind: 'retry' }; @@ -834,7 +834,16 @@ export class SyncService { [this.status, this.error] = ['offline', error.message]; return { kind: 'retry' }; } - if (error instanceof SyncSetupError || error instanceof SyncFileDamagedError) return this.attend('failed', error.message); - return this.attend('failed', `Sync stopped: ${error.message}`); + return this.retryQuietly(error.message); + } + + // Anything that is not a choice for the user, a lost sign-in or a sign of tampering is tried + // again on the scheduler's back-off: most clear up on their own (a sync file another computer is + // writing, an update that adds a newer format), and "Try again" was all the user could do. + // Each new problem is journalled once, not on every retry. + private retryQuietly(message: string): RunResult { + if (message !== this.error) this.deps.journal(`Sync will try again: ${message}`); + [this.status, this.error] = ['retrying', message]; + return { kind: 'retry' }; } } diff --git a/electron/window-bounds.test.ts b/electron/window-bounds.test.ts new file mode 100644 index 0000000..57f5550 --- /dev/null +++ b/electron/window-bounds.test.ts @@ -0,0 +1,62 @@ +import assert from 'node:assert/strict'; +import { promises as fs } from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { test } from 'node:test'; +import type { BrowserWindow } from 'electron'; +import { parsePlacement, restoredBounds, WindowBounds } from './window-bounds'; + +const minimum = { width: 960, height: 600 }; +const laptop = { x: 0, y: 25, width: 1440, height: 875 }; +const monitor = { x: 1440, y: 0, width: 2560, height: 1440 }; + +test('a window comes back where it was left while that place is on a display', () => { + assert.deepEqual(restoredBounds({ x: 1600, y: 100, width: 1800, height: 1100 }, [laptop, monitor], minimum), { x: 1600, y: 100, width: 1800, height: 1100 }); +}); + +test('a window left on a display that is gone opens centred on the primary one, shrunk to fit', () => { + assert.deepEqual(restoredBounds({ x: 1600, y: 100, width: 1800, height: 1100 }, [laptop], minimum), { width: 1440, height: 875 }); +}); + +test('saved bounds never go below the minimum size', () => { + assert.deepEqual(restoredBounds({ x: 10, y: 40, width: 200, height: 100 }, [laptop], minimum), { x: 10, y: 40, width: 960, height: 600 }); +}); + +test('an unreadable placement is ignored', () => { + assert.equal(parsePlacement({ bounds: { x: 0, y: 0, width: 'wide' } }), null); + assert.equal(parsePlacement(null), null); + assert.deepEqual(parsePlacement({ bounds: { x: 1, y: 2, width: 3, height: 4 }, isMaximized: true }), { bounds: { x: 1, y: 2, width: 3, height: 4 }, isMaximized: true, isFullScreen: false }); +}); + +test('without a saved placement the window keeps its default size', async () => { + const bounds = new WindowBounds(path.join(await fs.mkdtemp(path.join(os.tmpdir(), 'openterm-window-')), 'window.json')); + await bounds.load(); + assert.deepEqual(bounds.options([laptop], minimum), {}); +}); + +test('the size a window is closed at is the size it opens at next time, maximised included', async () => { + const file = path.join(await fs.mkdtemp(path.join(os.tmpdir(), 'openterm-window-')), 'window.json'); + const handlers = new Map void>(); + const window = { + isDestroyed: () => false, isMinimized: () => false, isMaximized: () => true, isFullScreen: () => false, + getNormalBounds: () => ({ x: 100, y: 80, width: 1200, height: 800 }), + on(name: string, handler: () => void) { handlers.set(name, handler); return this; }, + once(name: string, handler: () => void) { handlers.set(name, handler); return this; }, + }; + const first = new WindowBounds(file); + await first.load(); + first.track(window as unknown as BrowserWindow); + handlers.get('close')!(); + const deadline = Date.now() + 10_000; + while (!await fs.stat(file).then(() => true, () => false)) { + if (Date.now() > deadline) throw new Error('window.json was never written'); + await new Promise((resolve) => setTimeout(resolve, 10)); + } + const next = new WindowBounds(file); + await next.load(); + assert.deepEqual(next.options([laptop], minimum), { x: 100, y: 80, width: 1200, height: 800 }); + let isMaximized = false; + next.track({ ...window, maximize: () => { isMaximized = true; } } as unknown as BrowserWindow); + handlers.get('ready-to-show')!(); + assert.equal(isMaximized, true); +}); diff --git a/electron/window-bounds.ts b/electron/window-bounds.ts new file mode 100644 index 0000000..aa1fcfd --- /dev/null +++ b/electron/window-bounds.ts @@ -0,0 +1,90 @@ +import type { BrowserWindow, Rectangle } from 'electron'; +import { JsonStore } from './json-store'; + +export interface WindowPlacement { + readonly bounds: Rectangle; + readonly isMaximized: boolean; + readonly isFullScreen: boolean; +} + +interface Size { + readonly width: number; + readonly height: number; +} + +const SAVE_DELAY_MS = 500; + +// A window must keep this much of its title bar on a display to come back where it was left. +const VISIBLE_PX = 100; + +// Windows reports a window snapped to the top edge a few pixels above the work area. +const EDGE_PX = 8; + +const isRectangle = (value: unknown): value is Rectangle => !!value && typeof value === 'object' + && ['x', 'y', 'width', 'height'].every((key) => Number.isFinite((value as Record)[key])); + +export function parsePlacement(value: unknown): WindowPlacement | null { + const saved = value as Partial> | null; + if (!saved || !isRectangle(saved.bounds)) return null; + return { bounds: saved.bounds, isMaximized: saved.isMaximized === true, isFullScreen: saved.isFullScreen === true }; +} + +// The saved bounds, fitted to the displays there are now: a window last left on a monitor that is +// gone opens centred on the primary display at its saved size, shrunk to fit. +export function restoredBounds(saved: Rectangle, workAreas: readonly Rectangle[], minimum: Size): Partial { + const isOnScreen = workAreas.some((area) => saved.x + saved.width - VISIBLE_PX >= area.x && saved.x + VISIBLE_PX <= area.x + area.width + && saved.y >= area.y - EDGE_PX && saved.y + VISIBLE_PX / 2 <= area.y + area.height); + const [primary] = workAreas; + const fit = (size: number, room: number, least: number) => Math.round(Math.max(least, Math.min(size, room))); + if (isOnScreen) return { x: Math.round(saved.x), y: Math.round(saved.y), width: fit(saved.width, Infinity, minimum.width), height: fit(saved.height, Infinity, minimum.height) }; + if (!primary) return { width: fit(saved.width, Infinity, minimum.width), height: fit(saved.height, Infinity, minimum.height) }; + return { width: fit(saved.width, primary.width, minimum.width), height: fit(saved.height, primary.height, minimum.height) }; +} + +// Remembers the main window's size, place and maximised or full-screen state in `window.json`. +// Bounds are the normal ones, so a maximised window still restores to the size it had before. +export class WindowBounds { + private placement: WindowPlacement | null = null; + private readonly store: JsonStore; + + constructor(file: string) { + this.store = new JsonStore(file, parsePlacement, () => null); + } + + async load(): Promise { + try { this.placement = await this.store.load(); } + catch { this.placement = null; } + } + + options(workAreas: readonly Rectangle[], minimum: Size): Partial { + return this.placement ? restoredBounds(this.placement.bounds, workAreas, minimum) : {}; + } + + // Call before the window's own ready-to-show listener: maximising shows the window on Windows. + track(window: BrowserWindow): void { + const restored = this.placement; + window.once('ready-to-show', () => { + if (restored?.isFullScreen) window.setFullScreen(true); + else if (restored?.isMaximized) window.maximize(); + }); + let timer: ReturnType | undefined; + const save = () => { + clearTimeout(timer); + timer = undefined; + if (window.isDestroyed() || window.isMinimized()) return; + this.placement = { bounds: window.getNormalBounds(), isMaximized: window.isMaximized(), isFullScreen: window.isFullScreen() }; + void this.store.save(this.placement).catch(() => undefined); + }; + const later = () => { + clearTimeout(timer); + timer = setTimeout(save, SAVE_DELAY_MS); + }; + window.on('resize', later); + window.on('move', later); + window.on('maximize', later); + window.on('unmaximize', later); + window.on('enter-full-screen', later); + window.on('leave-full-screen', later); + window.on('close', save); + } +} diff --git a/packages/meridian-charts/src/ui/styles.ts b/packages/meridian-charts/src/ui/styles.ts index 3ff1a79..554301e 100644 --- a/packages/meridian-charts/src/ui/styles.ts +++ b/packages/meridian-charts/src/ui/styles.ts @@ -34,8 +34,12 @@ const css = ` .mc-star.is-on { color: #f7a600; } .mc-star:hover { color: #f7a600; } -.mc-favorites { position: absolute; top: 8px; left: 50%; transform: translateX(-50%); z-index: 5; display: flex; gap: 2px; padding: 2px; border-radius: 6px; background: var(--mc-surface); border: 1px solid var(--mc-border); box-shadow: 0 2px 8px rgb(0 0 0 / 0.25); } +.mc-favorites { position: absolute; top: 8px; left: 50%; transform: translateX(-50%); z-index: 5; display: flex; align-items: center; gap: 2px; padding: 2px 2px 2px 0; border-radius: 6px; background: var(--mc-surface); border: 1px solid var(--mc-border); box-shadow: 0 2px 8px rgb(0 0 0 / 0.25); } +.mc-favorites-list { display: flex; gap: 2px; } .mc-favorites .mc-btn { width: 32px; height: 32px; } +.mc-favorites-handle { display: flex; align-items: center; justify-content: center; width: 14px; height: 32px; color: var(--mc-muted); cursor: grab; touch-action: none; } +.mc-favorites-handle:active { cursor: grabbing; } +.mc-favorites-handle svg { width: 24px; height: 24px; margin: 0 -5px; } .mc-legend { position: absolute; left: 8px; z-index: 3; display: flex; flex-direction: column; gap: 2px; max-width: calc(100% - 90px); pointer-events: none; } .mc-legend-row { display: flex; align-items: center; gap: 6px; height: 20px; padding: 0 4px; border-radius: 4px; white-space: nowrap; pointer-events: auto; font-size: 12px; } diff --git a/packages/meridian-charts/src/ui/toolbar.ts b/packages/meridian-charts/src/ui/toolbar.ts index 07af955..2d741f6 100644 --- a/packages/meridian-charts/src/ui/toolbar.ts +++ b/packages/meridian-charts/src/ui/toolbar.ts @@ -31,17 +31,30 @@ export interface ToolbarActions { const MEASURE = 'measure'; const ZOOM = 'zoom-in'; +const FAVORITES_POSITION_KEY = 'meridian.favorites.position'; + +function loadFavoritesPosition(): { x: number; y: number } | null { + try { + const saved = JSON.parse(localStorage.getItem(FAVORITES_POSITION_KEY) ?? 'null'); + return saved && Number.isFinite(saved.x) && Number.isFinite(saved.y) ? { x: saved.x, y: saved.y } : null; + } catch { + return null; + } +} // The drawing toolbar down the left of the chart. Each group button shows the tool last used // from it; its arrow opens the group's flyout, split into sections, where tools can be starred -// into the favourites bar. +// into the favourites bar, which floats over the charts and can be dragged anywhere on them. export class DrawingToolbar { readonly element: HTMLElement; private readonly lastUsed = new Map(toolGroups.map((group) => [group.id, group.sections[0].tools[0].type])); private flyout: HTMLElement | null = null; private openArrow: HTMLElement | null = null; private state: ToolbarState; + private favoritesPosition = loadFavoritesPosition(); private readonly favoritesBar: HTMLElement; + private readonly favoritesList: HTMLElement; + private readonly hostResize: ResizeObserver; constructor(host: HTMLElement, private readonly overlayHost: HTMLElement, private readonly actions: ToolbarActions, state: ToolbarState) { this.state = state; @@ -52,6 +65,15 @@ export class DrawingToolbar { this.favoritesBar = element('div', 'mc-favorites', overlayHost); this.favoritesBar.setAttribute('role', 'toolbar'); this.favoritesBar.setAttribute('aria-label', 'Favorite drawing tools'); + const handle = element('span', 'mc-favorites-handle', this.favoritesBar); + handle.innerHTML = iconSvg('drag-handle', 24); + handle.title = 'Move'; + handle.addEventListener('pointerdown', this.onDragFavorites); + this.favoritesList = element('div', 'mc-favorites-list', this.favoritesBar); + // From the host's own window: a popped-out chart lives in another document. + const view = overlayHost.ownerDocument.defaultView ?? window; + this.hostResize = new view.ResizeObserver(() => this.placeFavorites()); + this.hostResize.observe(overlayHost); host.ownerDocument.addEventListener('pointerdown', this.onOutside, true); this.render(); } @@ -59,6 +81,7 @@ export class DrawingToolbar { destroy(): void { this.element.ownerDocument.removeEventListener('pointerdown', this.onOutside, true); this.closeFlyout(); + this.hostResize.disconnect(); this.element.remove(); this.favoritesBar.remove(); } @@ -145,14 +168,57 @@ export class DrawingToolbar { } private renderFavorites(): void { - this.favoritesBar.replaceChildren(); + this.favoritesList.replaceChildren(); for (const type of this.state.favorites) { const info = drawingToolInfo.get(type); - if (info) this.button(this.favoritesBar, type, info.label, this.state.tool === type, () => this.actions.selectTool(this.state.tool === type ? null : type)); + if (info) this.button(this.favoritesList, type, info.label, this.state.tool === type, () => this.actions.selectTool(this.state.tool === type ? null : type)); } this.favoritesBar.style.display = this.state.favorites.length && this.isVisible ? '' : 'none'; + this.placeFavorites(); + } + + // Kept inside the charts when they shrink, or when a favourite added makes the bar longer. + private placeFavorites(): void { + const bar = this.favoritesBar; + if (!this.favoritesPosition) { + bar.style.left = '50%'; + bar.style.top = '8px'; + bar.style.transform = 'translateX(-50%)'; + return; + } + const box = this.overlayHost.getBoundingClientRect(); + bar.style.transform = 'none'; + bar.style.left = `${Math.max(0, Math.min(box.width - bar.offsetWidth, this.favoritesPosition.x))}px`; + bar.style.top = `${Math.max(0, Math.min(box.height - bar.offsetHeight, this.favoritesPosition.y))}px`; } + private onDragFavorites = (event: PointerEvent): void => { + if (event.button !== 0) return; + event.preventDefault(); + const bar = this.favoritesBar; + const handle = event.currentTarget as HTMLElement; + const box = this.overlayHost.getBoundingClientRect(); + const at = bar.getBoundingClientRect(); + const start = { x: event.clientX, y: event.clientY, left: at.left - box.left, top: at.top - box.top }; + handle.setPointerCapture(event.pointerId); + const move = (moveEvent: PointerEvent) => { + this.favoritesPosition = { + x: Math.max(0, Math.min(box.width - bar.offsetWidth, start.left + moveEvent.clientX - start.x)), + y: Math.max(0, Math.min(box.height - bar.offsetHeight, start.top + moveEvent.clientY - start.y)), + }; + this.placeFavorites(); + }; + const end = () => { + handle.removeEventListener('pointermove', move); + handle.removeEventListener('pointerup', end); + handle.removeEventListener('pointercancel', end); + try { localStorage.setItem(FAVORITES_POSITION_KEY, JSON.stringify(this.favoritesPosition)); } catch { /* The place then lasts for this session. */ } + }; + handle.addEventListener('pointermove', move); + handle.addEventListener('pointerup', end); + handle.addEventListener('pointercancel', end); + }; + private place(menu: HTMLElement, anchor: HTMLElement): void { const hostBox = this.overlayHost.getBoundingClientRect(); const box = anchor.getBoundingClientRect(); diff --git a/shared/sync.ts b/shared/sync.ts index ec4e380..7d8b8a6 100644 --- a/shared/sync.ts +++ b/shared/sync.ts @@ -99,6 +99,7 @@ export const syncStatuses = [ { key: 'offline', label: 'Offline' }, { key: 'waiting', label: 'Waiting for GitHub' }, { key: 'loading', label: 'Waiting for the app window' }, + { key: 'retrying', label: 'Retrying' }, { key: 'attention', label: 'Needs attention' }, ] as const; @@ -106,7 +107,7 @@ export type SyncStatus = (typeof syncStatuses)[number]['key']; export type SyncAttentionReason = | 'tampered' | 'rollback' | 'epoch' | 'tooNew' | 'stale' | 'revoked' - | 'held' | 'join' | 'reconnect' | 'repositoryPublic' | 'repositoryMissing' | 'failed'; + | 'held' | 'join' | 'reconnect' | 'repositoryPublic' | 'repositoryMissing'; export interface SyncMassChange { readonly kind: SyncKind; diff --git a/src/components/sync/SyncDialog.tsx b/src/components/sync/SyncDialog.tsx index 0714ba8..28d8e9a 100644 --- a/src/components/sync/SyncDialog.tsx +++ b/src/components/sync/SyncDialog.tsx @@ -382,7 +382,7 @@ function OnPanel({ view }: SyncStepProps) { {view.attention && } {!view.isRecoveryConfirmed &&

The recovery code for this sync was never confirmed. Make a new one and save it.

} - {view.status === 'offline' && view.error &&

{view.error} OpenTerm5 keeps your edits and tries again.

} + {(view.status === 'offline' || view.status === 'retrying') && view.error &&

{view.error} OpenTerm5 keeps your edits and tries again.

}

Layouts, charts, drawings, watchlists, templates, alerts, Pine scripts, saved accounts and settings stay the same on your computers. Panels, and which layout is in front, stay with each one.

diff --git a/src/components/sync/SyncStatus.tsx b/src/components/sync/SyncStatus.tsx index 2b9f898..21b7748 100644 --- a/src/components/sync/SyncStatus.tsx +++ b/src/components/sync/SyncStatus.tsx @@ -2,18 +2,28 @@ import { syncStatuses } from '../../../shared/sync'; import { syncStore } from '../../lib/sync'; import { useStore } from '../../lib/store'; import { openDialog } from '../../lib/workspace'; +import { Icon } from '../ui/Icon'; -const tones = { idle: 'is-good', syncing: '', offline: 'is-warn', waiting: 'is-warn', loading: 'is-warn', attention: 'is-bad' } as const; - +// A quiet icon while sync looks after itself, words only when it needs the user. export function SyncStatus() { const view = useStore(syncStore, (state) => state.view); + const status = useStore(syncStore, (state) => state.settled); if (!view || (view.phase !== 'on' && view.phase !== 'savingCode')) return null; const isAsked = view.pairingRequests.length > 0; - const label = isAsked ? 'a computer asks to join' : syncStatuses.find((status) => status.key === view.status)?.label ?? ''; - const title = view.attention?.message ?? (view.lastSyncedAt ? `Last synced ${new Date(view.lastSyncedAt).toLocaleTimeString()}` : 'Sync'); + const label = syncStatuses.find((item) => item.key === status)?.label ?? ''; + if (isAsked || status === 'attention') { + const text = isAsked ? 'A computer asks to join' : 'Sync needs you'; + return ( + + ); + } + const when = view.lastSyncedAt ? ` Last synced ${new Date(view.lastSyncedAt).toLocaleTimeString()}.` : ''; + const detail = status === 'idle' ? '' : `${view.error ? ` ${view.error}` : ''} Your edits are kept and sync tries again by itself.`; return ( - ); } diff --git a/src/components/ui/Icon.tsx b/src/components/ui/Icon.tsx index a0a7ec9..330472e 100644 --- a/src/components/ui/Icon.tsx +++ b/src/components/ui/Icon.tsx @@ -56,6 +56,9 @@ const paths = { expand: , compress: , popout: <>, + cloudSynced: <>, + cloudPaused: <>, + cloudAttention: <>, dock: <>, } as const; diff --git a/src/lib/drawing-tools-model.test.ts b/src/lib/drawing-tools-model.test.ts new file mode 100644 index 0000000..e353fae --- /dev/null +++ b/src/lib/drawing-tools-model.test.ts @@ -0,0 +1,15 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { defaultDrawingTools, parseDrawingTools, savedDrawingTools } from './drawing-tools-model'; + +test('saved rail switches come back, and anything unreadable falls back to the defaults', () => { + assert.deepEqual(parseDrawingTools({ cursor: 'dot', magnet: 'strong', isStayMode: true, isLocked: true, isHidden: false }), { cursor: 'dot', magnet: 'strong', isStayMode: true, isLocked: true, isHidden: false }); + assert.deepEqual(parseDrawingTools({ cursor: 'eraser', magnet: 'huge', isStayMode: 'yes' }), defaultDrawingTools); + assert.deepEqual(parseDrawingTools(null), defaultDrawingTools); +}); + +test('the tool in hand is not saved with the switches', () => { + const saved = savedDrawingTools({ tool: 'trend-line', cursor: 'dot', magnet: 'weak', isStayMode: true, isLocked: false, isHidden: true }); + assert.equal('tool' in saved, false); + assert.deepEqual(parseDrawingTools(JSON.parse(JSON.stringify(saved))), saved); +}); diff --git a/src/lib/drawing-tools-model.ts b/src/lib/drawing-tools-model.ts new file mode 100644 index 0000000..10d4427 --- /dev/null +++ b/src/lib/drawing-tools-model.ts @@ -0,0 +1,26 @@ +import type { CursorMode, MagnetMode, MeridianDrawingTools } from '@meridian/charts'; + +export type SavedDrawingTools = Omit; + +// The eraser is left out: a restart that kept it would delete the first drawing clicked. +const savedCursors: readonly CursorMode[] = ['cross', 'dot', 'arrow-cursor']; +const magnets: readonly MagnetMode[] = ['off', 'weak', 'strong']; + +export const defaultDrawingTools: SavedDrawingTools = { cursor: 'cross', magnet: 'off', isStayMode: false, isLocked: false, isHidden: false }; + +export function parseDrawingTools(value: unknown): SavedDrawingTools { + if (!value || typeof value !== 'object') return defaultDrawingTools; + const saved = value as Partial>; + const flag = (key: 'isStayMode' | 'isLocked' | 'isHidden') => typeof saved[key] === 'boolean' ? saved[key] : defaultDrawingTools[key]; + return { + cursor: savedCursors.find((cursor) => cursor === saved.cursor) ?? defaultDrawingTools.cursor, + magnet: magnets.find((magnet) => magnet === saved.magnet) ?? defaultDrawingTools.magnet, + isStayMode: flag('isStayMode'), + isLocked: flag('isLocked'), + isHidden: flag('isHidden'), + }; +} + +export function savedDrawingTools({ cursor, magnet, isStayMode, isLocked, isHidden }: MeridianDrawingTools): SavedDrawingTools { + return { cursor, magnet, isStayMode, isLocked, isHidden }; +} diff --git a/src/lib/drawing-tools.ts b/src/lib/drawing-tools.ts index bc6fac4..f833c75 100644 --- a/src/lib/drawing-tools.ts +++ b/src/lib/drawing-tools.ts @@ -1,4 +1,6 @@ import { drawingFavorites, saveDrawingFavorites, type MeridianChart, type MeridianDrawingTools } from '@meridian/charts'; +import { defaultDrawingTools, parseDrawingTools, savedDrawingTools, type SavedDrawingTools } from './drawing-tools-model'; +import { log } from './session'; import { Store } from './store'; import { tools, workspace } from './workspace'; @@ -11,9 +13,19 @@ export interface DrawingToolsState extends MeridianDrawingTools { readonly favorites: readonly string[]; } +const STORAGE_KEY = 'openterm.drawing-tools.v1'; + const engines = new Set(); -export const drawingTools = new Store({ tool: null, cursor: 'cross', magnet: 'off', isStayMode: false, isLocked: false, isHidden: false, favorites: drawingFavorites() }); +function load(): SavedDrawingTools { + try { + return parseDrawingTools(JSON.parse(localStorage.getItem(STORAGE_KEY) ?? 'null')); + } catch { + return defaultDrawingTools; + } +} + +export const drawingTools = new Store({ tool: null, ...load(), favorites: drawingFavorites() }); export function setDrawingTools(patch: Partial): void { drawingTools.set(patch); @@ -42,6 +54,21 @@ export function attachDrawingTools(engine: MeridianChart): () => void { }; } +// The rail's switches outlast a restart, as TradingView's do; the tool in hand does not. +export function startDrawingTools(): void { + let saved = ''; + drawingTools.subscribe(() => { + const next = JSON.stringify(savedDrawingTools(drawingTools.get())); + if (next === saved) return; + saved = next; + try { + localStorage.setItem(STORAGE_KEY, next); + } catch (error) { + log(`Drawing tool settings could not be saved: ${(error as Error).message}`, 'Charts'); + } + }); +} + // The terminal's own quick tools (Insert menu, shortcuts) pick a rail tool; when the rail moves // on to something else, the quick tool goes back to the cursor. let appTool = workspace.get().tool; diff --git a/src/lib/sync.ts b/src/lib/sync.ts index 41ee8bb..d43c8ba 100644 --- a/src/lib/sync.ts +++ b/src/lib/sync.ts @@ -1,4 +1,4 @@ -import type { SyncApi, SyncMethod, SyncMethods, SyncSnapshot, SyncSourceRequest, SyncView } from '../../shared/sync'; +import type { SyncApi, SyncMethod, SyncMethods, SyncSnapshot, SyncSourceRequest, SyncStatus, SyncView } from '../../shared/sync'; import { Store } from './store'; import { syncedStores, syncSources } from './sync-sources'; import { toJson } from './sync-model'; @@ -13,7 +13,13 @@ declare global { export const sync = window.sync; -export const syncStore = new Store<{ view: SyncView | null }>({ view: null }); +// `settled` is how the last run ended: a run starts every 15 s, and the status bar shows that +// rather than flickering to "syncing" on each one. +export const syncStore = new Store<{ view: SyncView | null; settled: SyncStatus }>({ view: null, settled: 'idle' }); + +function showView(view: SyncView): void { + syncStore.set((state) => ({ view, settled: view.status === 'syncing' ? state.settled : view.status })); +} // Store changes made by applying synced records are not news to the main process. let isApplying = false; @@ -35,8 +41,8 @@ async function serve(request: SyncSourceRequest): Promise { } export function startSync(): void { - sync.on('view', (view) => syncStore.set({ view })); - void sync.request('sync.view', {}).then((view) => syncStore.set({ view })).catch(() => undefined); + sync.on('view', showView); + void sync.request('sync.view', {}).then(showView).catch(() => undefined); let noticeTimer: ReturnType | undefined; const notice = () => { if (isApplying || noticeTimer || syncStore.get().view?.phase !== 'on') return; @@ -53,7 +59,7 @@ export function startSync(): void { export async function requestSync(method: M, params: SyncMethods[M][0]): Promise { try { const result = await sync.request(method, params); - if (result && typeof result === 'object' && 'phase' in result) syncStore.set({ view: result as SyncView }); + if (result && typeof result === 'object' && 'phase' in result) showView(result as SyncView); return null; } catch (error) { return (error as Error).message; diff --git a/src/main.tsx b/src/main.tsx index 55be358..bf7677e 100644 --- a/src/main.tsx +++ b/src/main.tsx @@ -21,6 +21,7 @@ import { startDrawingTemplates } from './lib/drawing-templates'; import { startPineScripts } from './lib/pine/pine-scripts'; import { startIndicatorFavorites } from './lib/indicator-favorites'; import { startTimeframeFavorites } from './lib/timeframe-favorites'; +import { startDrawingTools } from './lib/drawing-tools'; import './styles.css'; document.body.classList.add(`platform-${window.terminal.platform}`); @@ -40,6 +41,7 @@ startImportedThemes(); startPineScripts(); startIndicatorFavorites(); startTimeframeFavorites(); +startDrawingTools(); startAutomation(); startJournaling(); startUpdates(); diff --git a/src/styles.css b/src/styles.css index 70dc396..590e12d 100644 --- a/src/styles.css +++ b/src/styles.css @@ -5221,17 +5221,20 @@ button.is-link { } .status-sync { + display: inline-flex; + align-items: center; + gap: 5px; background: transparent; box-shadow: none; border-radius: 0; min-height: 0; - padding: 0 10px; + padding: 0 8px; color: var(--muted); + opacity: 0.7; } -.status-sync.is-good { color: var(--good); } -.status-sync.is-warn { color: var(--warn); } -.status-sync.is-bad { color: var(--bad); } +.status-sync:hover { opacity: 1; } +.status-sync.is-warn { color: var(--warn); opacity: 1; } .sync-steps { margin: 0 0 12px;