diff --git a/CHANGELOG.md b/CHANGELOG.md index af99face..24f19bd6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,8 +7,14 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0. ## Unreleased +### Added + +- **Find supports regular expressions.** A `.*` toggle in the Find bar switches the query to a regex (the case toggle still applies); an invalid pattern shows `Invalid`, with the compile error on hover. Filters and Highlight Rules already took regex. + ### Fixed +- **The MCP `rxstream` buffer is capped.** A session that subscribed but never read the resource held the entire serial stream in main-process memory for the life of the app; `RxStreamBuffer` keeps the last 1,000,000 characters, drops the oldest, and prefixes the next read with a one-line notice of how much was dropped. +- **Closing the window now stops the CPU-usage monitor and the flow-control poll.** `stopCpuMonitoring` was an empty method and `ConnController.cleanup` never cleared the 1s `getFlowControlSignals` interval; both are now cancelled, and the poll logs rather than throws on a bad IPC response. - **Toggling ANSI parsing from a fake port now sticks.** `FakePortsController` wrote `rxSettings.ansiEscapeCodeParsingEnabled` directly, which only ever reached the runtime copy of the setting; the persisted value kept the old state and a preset or restart silently reverted it. Seven such writes now go through the setter — and the settings classes no longer *have* a runtime copy to bypass. - **Applying a preset that names a serial port now connects to that port.** `setSelectedPort` wrote a `serialPortInfo` field nothing read, so the open used whichever port was selected in the UI — or failed outright — while the snackbar reported the preset's port. The serial reconnection poller went through the same call and was equally ineffective. - **Packaged builds no longer download the React DevTools extension on every launch.** `installExtension` ran unconditionally, so a shipped build fetched an extension from Google's CDN at startup and installed it with file access; now guarded by `app.isPackaged`. diff --git a/TODO.md b/TODO.md index 4f55bc22..c475c85c 100644 --- a/TODO.md +++ b/TODO.md @@ -269,7 +269,7 @@ The CHANGELOG shows this is a bug factory: IPC-serialising a JS number array. Store `Uint8Array` chunks in a **plain** (non-observable) array and concat once at write time. -- [ ] **MCP `rxBuffer` grows without bound.** `mcpService.ts:170`. +- [x] **MCP `rxBuffer` grows without bound.** (done 2026-09-05, `RxStreamBuffer`) `mcpService.ts:170`. `session.rxBuffer.text += text` on every RX chunk, cleared only when a client *reads* the resource. A client that subscribes and never reads (or disconnects without closing the session) leaks the entire stream into @@ -278,11 +278,11 @@ The CHANGELOG shows this is a bug factory: - [x] **React DevTools installs in production.** (done 2026-09-04) Guarded with `if (!app.isPackaged)`. -- [ ] **`stopCpuMonitoring()` is a no-op.** `App.tsx:437-440`. The +- [x] **`stopCpuMonitoring()` is a no-op.** (done 2026-09-05) `App.tsx:437-440`. The `requestAnimationFrame` loop it claims to stop keeps running. Capture the rAF handle and cancel it. -- [ ] **Find is substring-only** while Filters and Highlight Rules both support +- [x] **Find is substring-only** (done 2026-09-05) while Filters and Highlight Rules both support regex. `SingleTerminal.ts:180-199` uses `indexOf`; compare `TerminalFilter.ts:45-76`. Inconsistent, and regex-in-find is what you actually want in a 100k-line scrollback. diff --git a/src/main/RxStreamBuffer.spec.ts b/src/main/RxStreamBuffer.spec.ts new file mode 100644 index 00000000..28b46510 --- /dev/null +++ b/src/main/RxStreamBuffer.spec.ts @@ -0,0 +1,51 @@ +import { describe, expect, test } from 'vitest'; + +import { RxStreamBuffer } from './RxStreamBuffer'; + +describe('RxStreamBuffer', () => { + test('drain returns what was appended and empties the buffer', () => { + const buf = new RxStreamBuffer(100); + buf.append('hello '); + buf.append('world'); + expect(buf.drain()).toBe('hello world'); + expect(buf.drain()).toBe(''); + expect(buf.length).toBe(0); + }); + + test('never grows past the cap plus the amortisation slack', () => { + const buf = new RxStreamBuffer(1000); + for (let i = 0; i < 10_000; i += 1) { + buf.append('0123456789'); + } + // Trim runs when a quarter over the cap, so the buffer can sit a little + // above it between trims, but it must never run away. + expect(buf.length).toBeLessThanOrEqual(1250); + }); + + test('drops the oldest data and says so once on the next drain', () => { + const buf = new RxStreamBuffer(10); + buf.append('aaaaaaaaaa'); // 10, at cap + buf.append('bbbbbbbbbb'); // 20, over the 12-char trim threshold -> keep last 10 + const out = buf.drain(); + expect(out.startsWith('[NinjaTerm: 10 characters of received data were dropped')).toBe(true); + expect(out.endsWith('\nbbbbbbbbbb')).toBe(true); + // The notice is not repeated on a clean read. + buf.append('cc'); + expect(buf.drain()).toBe('cc'); + }); + + test('a drain never returns more than the cap, even inside the slack window', () => { + const buf = new RxStreamBuffer(10); + buf.append('aaaaaaaaaaaa'); // 12: over cap, but at the threshold, so not yet trimmed + expect(buf.length).toBe(12); + const out = buf.drain(); + const data = out.slice(out.indexOf('\n') + 1); + expect(data).toBe('aaaaaaaaaa'); + expect(out).toContain('2 characters'); + }); + + test('rejects a nonsensical cap', () => { + expect(() => new RxStreamBuffer(0)).toThrow(); + expect(() => new RxStreamBuffer(1.5)).toThrow(); + }); +}); diff --git a/src/main/RxStreamBuffer.ts b/src/main/RxStreamBuffer.ts new file mode 100644 index 00000000..2fc56851 --- /dev/null +++ b/src/main/RxStreamBuffer.ts @@ -0,0 +1,74 @@ +/** + * Bounded text buffer for the MCP `rxstream` resource. + * + * One of these exists per MCP session. Received text is appended as it + * arrives and drained when the client reads the resource. Before this + * existed the buffer was a bare string that only ever shrank on a read, so a + * client that subscribed and never read (or dropped its connection without + * closing the session) leaked the entire serial stream into main-process + * memory for as long as the app ran. + * + * The cap is drop-oldest: once the buffer would exceed `maxChars`, the front + * is discarded and the number of dropped characters is remembered so the next + * `drain()` can tell the client the stream has a gap rather than handing it + * a silently truncated mid-line join. + */ +export class RxStreamBuffer { + private text = ''; + + /** Characters discarded since the last `drain()`. */ + private droppedChars = 0; + + /** + * @param maxChars Most characters kept. Once exceeded the oldest are dropped. + * Trimming is amortised — it runs when the buffer is a quarter over the + * cap, not on every chunk — so a saturated stream costs one copy per + * `maxChars / 4` characters received rather than one per chunk. + */ + constructor(private readonly maxChars: number) { + if (!Number.isInteger(maxChars) || maxChars <= 0) { + throw new Error(`RxStreamBuffer maxChars must be a positive integer, got ${maxChars}`); + } + } + + get length(): number { + return this.text.length; + } + + append(chunk: string): void { + this.text += chunk; + const trimThreshold = this.maxChars + Math.floor(this.maxChars / 4); + if (this.text.length > trimThreshold) { + this._trimToCap(); + } + } + + /** + * Returns everything buffered and empties the buffer. If anything was + * dropped since the previous drain, a single notice line precedes the data + * so the reader knows there is a gap. + */ + drain(): string { + // A read must never hand back more than the cap either, so trim any + // amortisation slack first. + if (this.text.length > this.maxChars) { + this._trimToCap(); + } + let out = this.text; + this.text = ''; + if (this.droppedChars > 0) { + out = `[NinjaTerm: ${this.droppedChars} characters of received data were dropped because the stream buffer overflowed]\n${out}`; + this.droppedChars = 0; + } + return out; + } + + private _trimToCap(): void { + const excess = this.text.length - this.maxChars; + if (excess <= 0) { + return; + } + this.droppedChars += excess; + this.text = this.text.slice(excess); + } +} diff --git a/src/main/mcpService.ts b/src/main/mcpService.ts index 46e351f3..e232bc64 100644 --- a/src/main/mcpService.ts +++ b/src/main/mcpService.ts @@ -7,15 +7,24 @@ import { randomUUID } from 'crypto'; import { BrowserWindow } from 'electron'; import { log } from './Logging'; +import { RxStreamBuffer } from './RxStreamBuffer'; import { getActivePortPath, writeToPort, listPorts } from './serialService'; const REQUEST_TIMEOUT_MS = 5000; +/** + * Most characters the `rxstream` resource holds per session between reads. + * Bounds main-process memory for a client that subscribes and never reads + * (or disconnects without closing its session). Comfortably above what a + * client polling every few seconds sees at typical serial rates. + */ +const RX_STREAM_BUFFER_MAX_CHARS = 1_000_000; + export class McpService { private httpServer: Server | null = null; private mainWindow: BrowserWindow | null = null; /** Active sessions keyed by session ID. A new entry is created for each initialize request. */ - private sessions = new Map(); + private sessions = new Map(); private registeredPort: number = 0; /** @@ -89,7 +98,7 @@ export class McpService { if (!sessionId) { // New session: create a fresh McpServer + transport pair - const rxBuffer = { text: '' }; + const rxBuffer = new RxStreamBuffer(RX_STREAM_BUFFER_MAX_CHARS); const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: () => randomUUID(), onsessioninitialized: (id) => { @@ -167,12 +176,12 @@ export class McpService { */ handleRxData(text: string) { for (const [, session] of this.sessions) { - session.rxBuffer.text += text; + session.rxBuffer.append(text); session.mcpServer.server.sendResourceUpdated({ uri: 'ninjaterm://terminal/rxstream' }).catch(() => {}); } } - private registerTools(server: McpServer, rxBuffer: { text: string }) { + private registerTools(server: McpServer, rxBuffer: RxStreamBuffer) { server.tool( 'get_terminal_output', @@ -256,11 +265,12 @@ export class McpService { description: 'Real-time stream of incoming serial data. Subscribe to receive push notifications ' + '(notifications/resources/updated) when new data arrives, then read this resource to ' + - 'retrieve buffered data since the last read. For historical data use the get_terminal_output tool.', + 'retrieve buffered data since the last read. For historical data use the get_terminal_output tool. ' + + `At most the last ${RX_STREAM_BUFFER_MAX_CHARS} characters are kept between reads; if the buffer ` + + 'overflows the oldest data is dropped and the next read starts with a one-line notice saying how much.', }, async () => { - const data = rxBuffer.text; - rxBuffer.text = ''; + const data = rxBuffer.drain(); return { contents: [{ uri: 'ninjaterm://terminal/rxstream', mimeType: 'text/plain', text: data }], }; diff --git a/src/renderer/src/model/App.spec.ts b/src/renderer/src/model/App.spec.ts index 3e3c0002..85dc3d5e 100644 --- a/src/renderer/src/model/App.spec.ts +++ b/src/renderer/src/model/App.spec.ts @@ -47,3 +47,25 @@ describe('App rate-tracking buffers', () => { expect(length).toBeLessThanOrEqual(4096); }); }); + +describe('App cleanup', () => { + beforeEach(() => { + window.localStorage.clear(); + }); + + test('cleanup cancels the CPU-monitor animation frame', () => { + const cancelSpy = vi.spyOn(window, 'cancelAnimationFrame'); + const app = new App(); + // The constructor scheduled a frame... + const handle = (app as any).cpuMonitorRafHandle; + expect(handle).not.toBeNull(); + + app.cleanup(); + + // ...and cleanup cancelled that exact frame. `stopCpuMonitoring` used to + // be an empty method, so the loop ran until the window unloaded. + expect(cancelSpy).toHaveBeenCalledWith(handle); + expect((app as any).cpuMonitorRafHandle).toBeNull(); + cancelSpy.mockRestore(); + }); +}); diff --git a/src/renderer/src/model/App.tsx b/src/renderer/src/model/App.tsx index c579b1fb..73e2bef2 100644 --- a/src/renderer/src/model/App.tsx +++ b/src/renderer/src/model/App.tsx @@ -131,6 +131,15 @@ export class App { // CPU monitoring variables - measuring overall renderer process load private readonly CPU_MEASUREMENT_WINDOW_MS = 1000; // 1 second window + /** + * The CPU monitor's pending animation frame, so `stopCpuMonitoring` can + * cancel it. Null when the monitor is not running. + */ + private cpuMonitorRafHandle: number | null = null; + + /** The CPU monitor's pending idle callback, if one is outstanding. */ + private cpuMonitorIdleHandle: number | null = null; + // If true app is being tested by code. // Used for force terminal height to value when browser is not // available to determine height @@ -273,6 +282,9 @@ export class App { // no subscriber. rxDataPoints: false, txDataPoints: false, + // Written once per animation frame; nothing observes them. + cpuMonitorRafHandle: false, + cpuMonitorIdleHandle: false, } as any); // Make sure this near the end } @@ -456,7 +468,8 @@ export class App { // Use requestIdleCallback to get more accurate idle time measurements if (typeof requestIdleCallback !== 'undefined') { - requestIdleCallback((deadline) => { + this.cpuMonitorIdleHandle = requestIdleCallback((deadline) => { + this.cpuMonitorIdleHandle = null; // If we have very little idle time, we're CPU bound const availableTime = deadline.timeRemaining(); if (availableTime < 1) { // Less than 1ms idle time indicates high CPU usage @@ -465,8 +478,9 @@ export class App { }); } - // Continue monitoring - requestAnimationFrame(measureCpuUsage); + // Continue monitoring. Keep the handle so `stopCpuMonitoring` can end + // the loop; before this it ran until the window unloaded. + this.cpuMonitorRafHandle = requestAnimationFrame(measureCpuUsage); }; measureCpuUsage(); @@ -476,8 +490,14 @@ export class App { * Stops CPU monitoring. */ private stopCpuMonitoring() { - // CPU monitoring is handled by requestAnimationFrame and requestIdleCallback - // These will stop when the window is unloaded + if (this.cpuMonitorRafHandle !== null) { + cancelAnimationFrame(this.cpuMonitorRafHandle); + this.cpuMonitorRafHandle = null; + } + if (this.cpuMonitorIdleHandle !== null && typeof cancelIdleCallback !== 'undefined') { + cancelIdleCallback(this.cpuMonitorIdleHandle); + this.cpuMonitorIdleHandle = null; + } } /** diff --git a/src/renderer/src/model/ConnController/ConnController.characterisation.spec.ts b/src/renderer/src/model/ConnController/ConnController.characterisation.spec.ts index cfb12fda..4cdf7ed4 100644 --- a/src/renderer/src/model/ConnController/ConnController.characterisation.spec.ts +++ b/src/renderer/src/model/ConnController/ConnController.characterisation.spec.ts @@ -1,4 +1,4 @@ -import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import type { Mock } from 'vitest'; import { App } from '../App'; @@ -107,6 +107,12 @@ describe('ConnController connection lifecycle', () => { conn = app.connController; }); + afterEach(() => { + // Tests that leave a port open have started the flow-control poll; without + // this it outlives the test and fires against a torn-down environment. + app.cleanup(); + }); + /** Points the app at a serial port and opens it. */ async function openSerial() { app.settings.portConfiguration.setConnectionType(ConnectionType.SERIAL_PORT); diff --git a/src/renderer/src/model/ConnController/ConnController.ts b/src/renderer/src/model/ConnController/ConnController.ts index f905157d..b3130d22 100644 --- a/src/renderer/src/model/ConnController/ConnController.ts +++ b/src/renderer/src/model/ConnController/ConnController.ts @@ -173,6 +173,10 @@ export class ConnController { cleanup() { this.stopPollingForReconnection(); + // Was missing, so the 1s flow-control poll outlived the controller: in the + // app it ran until the window unloaded, and in tests a leaked interval + // fired after the file was torn down and surfaced as an unhandled rejection. + this.stopFlowControlPolling(); this.disposeConnListeners(); } @@ -349,16 +353,22 @@ export class ConnController { if (portPath === null) { return; } - const response = await window.electronAPI.serial.getFlowControlSignals(portPath); - if (!response.success) { - console.error('Error getting flow control signals:', response.error); - return; + // An async interval callback has nobody awaiting it, so anything thrown + // here is an unhandled rejection. Log and try again next tick instead. + try { + const response = await window.electronAPI.serial.getFlowControlSignals(portPath); + if (!response?.success) { + console.error('Error getting flow control signals:', response?.error); + return; + } + runInAction(() => { + this.currentFlowControlState.dsr = response.signals?.dsr || false; + this.currentFlowControlState.cts = response.signals?.cts || false; + this.currentFlowControlState.dcd = response.signals?.dcd || false; + }); + } catch (error) { + console.error('Error getting flow control signals:', error); } - runInAction(() => { - this.currentFlowControlState.dsr = response.signals!.dsr || false; - this.currentFlowControlState.cts = response.signals!.cts || false; - this.currentFlowControlState.dcd = response.signals!.dcd || false; - }); }, 1000); } diff --git a/src/renderer/src/model/Terminals/SingleTerminal/Find.spec.ts b/src/renderer/src/model/Terminals/SingleTerminal/Find.spec.ts index ae748345..0fd9c75d 100644 --- a/src/renderer/src/model/Terminals/SingleTerminal/Find.spec.ts +++ b/src/renderer/src/model/Terminals/SingleTerminal/Find.spec.ts @@ -186,4 +186,59 @@ describe('find-in-scrollback', () => { const bananaRowIdx = terminal.filteredTerminalRows.findIndex((r) => r.text.startsWith('banana')); expect(bananaRowIdx).toBe(-1); }); + + test('regex mode finds every match of a pattern', () => { + terminal.parseData(stringToUint8Array('err1 err22\nok\nerr333\n'), DataDirection.RX); + terminal.openFind(); + terminal.setFindUseRegex(true); + terminal.setFindQuery('err\\d+'); + expect(terminal.findMatches).toEqual([ + { rowIndex: 0, colStart: 0, colEnd: 4 }, + { rowIndex: 0, colStart: 5, colEnd: 10 }, + { rowIndex: 2, colStart: 0, colEnd: 6 }, + ]); + }); + + test('regex mode honours the case-sensitivity toggle', () => { + terminal.parseData(stringToUint8Array('Error error ERROR\n'), DataDirection.RX); + terminal.openFind(); + terminal.setFindUseRegex(true); + terminal.setFindQuery('error'); + expect(terminal.findMatches.length).toBe(3); + terminal.setFindCaseSensitive(true); + expect(terminal.findMatches).toEqual([{ rowIndex: 0, colStart: 6, colEnd: 11 }]); + }); + + test('an invalid regex yields no matches and an error message rather than throwing', () => { + terminal.parseData(stringToUint8Array('hello\n'), DataDirection.RX); + terminal.openFind(); + terminal.setFindUseRegex(true); + terminal.setFindQuery('[unclosed'); + expect(terminal.findMatches).toEqual([]); + expect(terminal.findRegex.errorMsg).not.toBe(''); + // Back in substring mode the same text is a literal that simply doesn't occur. + terminal.setFindUseRegex(false); + expect(terminal.findRegex.errorMsg).toBe(''); + expect(terminal.findMatches).toEqual([]); + }); + + test('zero-width regex matches neither hang nor get reported', () => { + terminal.parseData(stringToUint8Array('abc\n'), DataDirection.RX); + terminal.openFind(); + terminal.setFindUseRegex(true); + terminal.setFindQuery('x*'); + expect(terminal.findMatches).toEqual([]); + terminal.setFindQuery('b*'); + expect(terminal.findMatches).toEqual([{ rowIndex: 0, colStart: 1, colEnd: 2 }]); + }); + + test('toggling regex mode resets the current match to the first', () => { + terminal.parseData(stringToUint8Array('aa aa aa\n'), DataDirection.RX); + terminal.openFind(); + terminal.setFindQuery('aa'); + terminal.nextMatch(); + expect(terminal.currentMatchIndex).toBe(1); + terminal.setFindUseRegex(true); + expect(terminal.currentMatchIndex).toBe(0); + }); }); diff --git a/src/renderer/src/model/Terminals/SingleTerminal/SingleTerminal.ts b/src/renderer/src/model/Terminals/SingleTerminal/SingleTerminal.ts index 3b73ed6a..aeda8c00 100644 --- a/src/renderer/src/model/Terminals/SingleTerminal/SingleTerminal.ts +++ b/src/renderer/src/model/Terminals/SingleTerminal/SingleTerminal.ts @@ -161,6 +161,13 @@ export class SingleTerminal { /** Whether the find query is matched case-sensitively. */ findCaseSensitive: boolean = false; + /** + * Whether the find query is a regular expression rather than a substring. + * Filters and highlight rules both take regex; find not doing so was the + * odd one out. + */ + findUseRegex: boolean = false; + /** Index into `findMatches` of the "current" match (the one auto-scrolled to). */ currentMatchIndex: number = 0; @@ -189,11 +196,28 @@ export class SingleTerminal { return this.filterController?.activeFilters ?? []; } + /** + * The compiled find regex when `findUseRegex` is on, plus the compile error + * for the Find bar to show. `regex` is null in substring mode, for an empty + * query, or when the pattern does not compile. Always compiled with `g` so + * `findMatches` can walk every hit in a row. + */ + get findRegex(): { regex: RegExp | null; errorMsg: string } { + if (!this.findUseRegex || this.findQuery === '') { + return { regex: null, errorMsg: '' }; + } + try { + return { regex: new RegExp(this.findQuery, this.findCaseSensitive ? 'g' : 'gi'), errorMsg: '' }; + } catch (e) { + return { regex: null, errorMsg: e instanceof Error ? e.message : 'Invalid regex' }; + } + } + /** * All matches of the active find query within `filteredTerminalRows`, in * top-to-bottom, left-to-right order. Empty when find is closed, the * query is empty, or there are no hits. Computed property — recomputed - * automatically when query, case-sensitivity, or rows change. + * automatically when query, case-sensitivity, regex mode, or rows change. */ get findMatches(): FindMatch[] { // Matches are computed from row text, which is not observable — see @@ -202,12 +226,32 @@ export class SingleTerminal { if (!this.isFindOpen || this.findQuery === '') { return []; } - const query = this.findCaseSensitive ? this.findQuery : this.findQuery.toLowerCase(); - if (query.length === 0) { - return []; - } const matches: FindMatch[] = []; const rows = this.filteredTerminalRows; + + if (this.findUseRegex) { + const re = this.findRegex.regex; + if (re === null) { + return []; + } + for (let rowIndex = 0; rowIndex < rows.length; rowIndex += 1) { + const rowText = rows[rowIndex].text; + re.lastIndex = 0; + let m: RegExpExecArray | null; + while ((m = re.exec(rowText)) !== null) { + if (m[0].length === 0) { + // A zero-width match (e.g. `x*` on a row with no x) has nothing to + // highlight and would never advance `lastIndex` on its own. + re.lastIndex += 1; + continue; + } + matches.push({ rowIndex, colStart: m.index, colEnd: m.index + m[0].length }); + } + } + return matches; + } + + const query = this.findCaseSensitive ? this.findQuery : this.findQuery.toLowerCase(); for (let rowIndex = 0; rowIndex < rows.length; rowIndex += 1) { const rowText = rows[rowIndex].text; const haystack = this.findCaseSensitive ? rowText : rowText.toLowerCase(); @@ -588,6 +632,7 @@ export class SingleTerminal { // notification propagate whenever a dependency actually changed. // Covered by `Reactivity.spec.ts`. filteredTerminalRows: computed({ equals: () => false }), + findRegex: computed, findMatches: computed, findMatchesByRow: computed, currentMatch: computed, @@ -2520,6 +2565,11 @@ export class SingleTerminal { this.currentMatchIndex = 0; } + setFindUseRegex(value: boolean) { + this.findUseRegex = value; + this.currentMatchIndex = 0; + } + /** Advance to the next match, wrapping to the start at the end. No-op if there are no matches. */ nextMatch() { const total = this.findMatches.length; diff --git a/src/renderer/src/view/Terminals/SingleTerminal/FindBar.tsx b/src/renderer/src/view/Terminals/SingleTerminal/FindBar.tsx index e72817cb..2b915752 100644 --- a/src/renderer/src/view/Terminals/SingleTerminal/FindBar.tsx +++ b/src/renderer/src/view/Terminals/SingleTerminal/FindBar.tsx @@ -54,8 +54,21 @@ export default observer((props: Props) => { const total = matches.length; const currentNumber = total === 0 ? 0 : terminal.currentMatchIndex + 1; const hasQuery = terminal.findQuery.length > 0; + const regexErrorMsg = terminal.findRegex.errorMsg; + const hasRegexError = regexErrorMsg !== ''; const noMatchesForQuery = hasQuery && total === 0; + const toggleSx = (on: boolean) => ({ + color: on ? '#ffb74d' : 'rgba(255, 255, 255, 0.6)', + padding: '2px 6px', + fontSize: '13px', + fontWeight: 600, + lineHeight: 1, + borderRadius: '3px', + // Outline the toggle when active so it reads as "on" even at a glance. + border: on ? '1px solid #ffb74d' : '1px solid transparent', + }); + return (
{ { textAlign: 'center', }} > - {hasQuery ? `${currentNumber} / ${total}` : ''} + {hasRegexError ? 'Invalid' : hasQuery ? `${currentNumber} / ${total}` : ''} terminal.setFindCaseSensitive(!terminal.findCaseSensitive)} - sx={{ - color: terminal.findCaseSensitive ? '#ffb74d' : 'rgba(255, 255, 255, 0.6)', - padding: '2px 6px', - fontSize: '13px', - fontWeight: 600, - lineHeight: 1, - borderRadius: '3px', - // Outline the toggle when active so it reads as "on" even at a glance. - border: terminal.findCaseSensitive ? '1px solid #ffb74d' : '1px solid transparent', - }} + sx={toggleSx(terminal.findCaseSensitive)} data-testid={`${terminal.id}-find-case-toggle`} > Aa + + terminal.setFindUseRegex(!terminal.findUseRegex)} + sx={toggleSx(terminal.findUseRegex)} + data-testid={`${terminal.id}-find-regex-toggle`} + > + .* + + + ({ }, })) +// jsdom does not implement media playback. `App.cleanup()` pauses the sound +// player's