Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
110 changes: 110 additions & 0 deletions src/renderer/src/lib/pane-manager/pane-terminal-mouse-wheel.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ import { afterEach, describe, expect, it, vi } from 'vitest'
import {
TERMINAL_TUI_MOUSE_WHEEL_MULTIPLIER,
attachTerminalMouseWheelMultiplier,
createTerminalTuiMouseWheelAccelerationState,
normalizeTerminalTuiMouseWheelMultiplier,
resolveTerminalTuiMouseWheelReportCount,
shouldMultiplyTerminalMouseWheel
} from './pane-terminal-mouse-wheel'

Expand Down Expand Up @@ -88,6 +90,49 @@ describe('terminal mouse wheel multiplier', () => {
expect(normalizeTerminalTuiMouseWheelMultiplier(20)).toBe(10)
})

it('keeps deliberate TUI wheel ticks precise even with a fast max', () => {
const state = createTerminalTuiMouseWheelAccelerationState()

const reports = [0, 200, 400, 600].map((timeStamp) =>
resolveTerminalTuiMouseWheelReportCount({ deltaY: 12, timeStamp }, 5, state)
)

expect(reports).toEqual([1, 1, 1, 1])
})

it('keeps the one-report setting precise even during fast TUI wheel bursts', () => {
const state = createTerminalTuiMouseWheelAccelerationState()

const reports = [0, 50, 100, 150, 200, 250].map((timeStamp) =>
resolveTerminalTuiMouseWheelReportCount({ deltaY: 12, timeStamp }, 1, state)
)

expect(reports).toEqual([1, 1, 1, 1, 1, 1])
})

it('accelerates repeated same-direction TUI wheel ticks with a front-loaded curve', () => {
const state = createTerminalTuiMouseWheelAccelerationState()

const reports = [0, 50, 100, 150, 200, 250].map((timeStamp) =>
resolveTerminalTuiMouseWheelReportCount({ deltaY: 12, timeStamp }, 5, state)
)

expect(reports).toEqual([1, 5, 5, 5, 5, 5])
})

it('resets TUI wheel acceleration when the user changes direction', () => {
const state = createTerminalTuiMouseWheelAccelerationState()

const reports = [
resolveTerminalTuiMouseWheelReportCount({ deltaY: 12, timeStamp: 0 }, 5, state),
resolveTerminalTuiMouseWheelReportCount({ deltaY: 12, timeStamp: 50 }, 5, state),
resolveTerminalTuiMouseWheelReportCount({ deltaY: -12, timeStamp: 100 }, 5, state),
resolveTerminalTuiMouseWheelReportCount({ deltaY: -12, timeStamp: 150 }, 5, state)
]

expect(reports).toEqual([1, 5, 1, 5])
})

it('multiplies discrete wheel events when mouse reporting is active', () => {
expect(shouldMultiplyTerminalMouseWheel(wheelEvent(), terminalElement())).toBe(true)
})
Expand Down Expand Up @@ -183,4 +228,69 @@ describe('terminal mouse wheel multiplier', () => {
expect(dispatched.map((entry) => entry.deltaY)).toEqual([1])
expect(shouldMultiplyTerminalMouseWheel(dispatched[0]!, target)).toBe(false)
})

it('paces accelerated TUI wheel reports after the immediate first report', async () => {
vi.stubGlobal('WheelEvent', TestWheelEvent)
const handlers: ((event: WheelEvent) => boolean)[] = []
const scheduledFrames: (() => void)[] = []
const target = Object.assign(new EventTarget(), {
classList: {
contains: (className: string) => className === 'enable-mouse-events'
}
}) as unknown as EventTarget & HTMLElement
const dispatched: WheelEvent[] = []
target.addEventListener('wheel', (event) => dispatched.push(event as WheelEvent))
attachTerminalMouseWheelMultiplier(
{
attachCustomWheelEventHandler: (handler) => {
handlers.push(handler)
},
element: target
},
{
getTuiMouseWheelMultiplier: () => 3,
scheduleWheelReplayFrame: (callback) => scheduledFrames.push(callback)
}
)
const firstEvent = new TestWheelEvent('wheel', {
bubbles: true,
cancelable: true,
deltaMode: DOM_DELTA_PIXEL,
deltaY: 12
}) as WheelEvent
Object.defineProperty(firstEvent, 'wheelDeltaY', {
configurable: true,
value: -120
})
Object.defineProperty(firstEvent, 'timeStamp', {
configurable: true,
value: 0
})
const secondEvent = new TestWheelEvent('wheel', {
bubbles: true,
cancelable: true,
deltaMode: DOM_DELTA_PIXEL,
deltaY: 12
}) as WheelEvent
Object.defineProperty(secondEvent, 'wheelDeltaY', {
configurable: true,
value: -120
})
Object.defineProperty(secondEvent, 'timeStamp', {
configurable: true,
value: 50
})

expect(handlers[0]?.(firstEvent)).toBe(false)
await Promise.resolve()
expect(dispatched).toHaveLength(1)

expect(handlers[0]?.(secondEvent)).toBe(false)
await Promise.resolve()
expect(dispatched).toHaveLength(2)
expect(scheduledFrames).toHaveLength(1)

scheduledFrames.shift()?.()
expect(dispatched).toHaveLength(4)
})
})
169 changes: 161 additions & 8 deletions src/renderer/src/lib/pane-manager/pane-terminal-mouse-wheel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ const DOM_DELTA_PIXEL = 0
const DOM_DELTA_LINE = 1
const DISCRETE_PIXEL_WHEEL_DELTA_MIN = 50
const LEGACY_MOUSE_WHEEL_DELTA_MIN = 100
const TUI_WHEEL_ACCELERATION_WINDOW_MS = 140
const TUI_WHEEL_REPORTS_PER_FRAME = 4

export const TERMINAL_TUI_MOUSE_WHEEL_MULTIPLIER = 1
export const TERMINAL_TUI_MOUSE_WHEEL_MULTIPLIER_MIN = 1
Expand All @@ -15,6 +17,7 @@ type TerminalWheelTarget = Pick<Terminal, 'attachCustomWheelEventHandler' | 'ele

type TerminalMouseWheelMultiplierOptions = {
getTuiMouseWheelMultiplier?: () => number | undefined
scheduleWheelReplayFrame?: (callback: () => void) => void
}

type ReplayedWheelEvent = WheelEvent & {
Expand All @@ -26,6 +29,40 @@ type WheelEventWithLegacyDelta = WheelEvent & {
wheelDeltaY?: number
}

export type TerminalTuiMouseWheelAccelerationState = {
lastDirection: -1 | 0 | 1
lastInputAt: number | null
streak: number
}

type TerminalTuiMouseWheelReplayState = {
acceleration: TerminalTuiMouseWheelAccelerationState
drainScheduled: boolean
pendingDirection: -1 | 0 | 1
pendingEvent: WheelEvent | null
pendingReports: number
pendingTarget: EventTarget | null
}

export function createTerminalTuiMouseWheelAccelerationState(): TerminalTuiMouseWheelAccelerationState {
return {
lastDirection: 0,
lastInputAt: null,
streak: 0
}
}

function createTerminalTuiMouseWheelReplayState(): TerminalTuiMouseWheelReplayState {
return {
acceleration: createTerminalTuiMouseWheelAccelerationState(),
drainScheduled: false,
pendingDirection: 0,
pendingEvent: null,
pendingReports: 0,
pendingTarget: null
}
}

function isReplayedWheelEvent(event: WheelEvent): boolean {
return (event as ReplayedWheelEvent)[REPLAYED_WHEEL_EVENT_PROPERTY] === true
}
Expand Down Expand Up @@ -61,6 +98,21 @@ function isDiscreteWheelEvent(event: WheelEvent): boolean {
return legacyDelta !== null && Math.abs(legacyDelta) >= LEGACY_MOUSE_WHEEL_DELTA_MIN
}

function wheelDirection(event: Pick<WheelEvent, 'deltaY'>): -1 | 1 {
return event.deltaY < 0 ? -1 : 1
}

function wheelInputTime(event: Pick<WheelEvent, 'timeStamp'>): number {
if (typeof event.timeStamp === 'number' && Number.isFinite(event.timeStamp)) {
return event.timeStamp
}
return performance.now()
}

function easeOutCubic(value: number): number {
return 1 - Math.pow(1 - value, 3)
}

function cloneWheelReportEvent(event: WheelEvent): WheelEvent {
const clone = new WheelEvent(event.type, {
bubbles: event.bubbles,
Expand Down Expand Up @@ -88,6 +140,34 @@ function cloneWheelReportEvent(event: WheelEvent): WheelEvent {
return clone
}

export function resolveTerminalTuiMouseWheelReportCount(
event: Pick<WheelEvent, 'deltaY' | 'timeStamp'>,
maxReports: number,
state: TerminalTuiMouseWheelAccelerationState
): number {
const normalizedMaxReports = normalizeTerminalTuiMouseWheelMultiplier(maxReports)
const direction = wheelDirection(event)
const currentInputAt = wheelInputTime(event)
const elapsedMs = state.lastInputAt === null ? null : currentInputAt - state.lastInputAt
const isAccelerating =
state.lastDirection === direction &&
elapsedMs !== null &&
elapsedMs >= 0 &&
elapsedMs <= TUI_WHEEL_ACCELERATION_WINDOW_MS

state.streak = isAccelerating ? state.streak + 1 : 0
state.lastDirection = direction
state.lastInputAt = currentInputAt

if (!isAccelerating || normalizedMaxReports <= 1 || elapsedMs === null) {
return 1
}

const cadence = 1 - elapsedMs / TUI_WHEEL_ACCELERATION_WINDOW_MS
const acceleratedReports = 1 + Math.round((normalizedMaxReports - 1) * easeOutCubic(cadence))
return Math.min(normalizedMaxReports, Math.max(1, acceleratedReports))
}

export function shouldMultiplyTerminalMouseWheel(
event: WheelEvent,
terminalElement: HTMLElement | null | undefined
Expand Down Expand Up @@ -117,10 +197,79 @@ export function normalizeTerminalTuiMouseWheelMultiplier(value: number | undefin
)
}

function defaultScheduleWheelReplayFrame(callback: () => void): void {
if (typeof requestAnimationFrame === 'function') {
requestAnimationFrame(() => callback())
return
}
setTimeout(callback, 0)
}

function drainTerminalTuiWheelReports(
state: TerminalTuiMouseWheelReplayState,
scheduleWheelReplayFrame: (callback: () => void) => void,
reportsThisFrame: number
): void {
const target = state.pendingTarget
const event = state.pendingEvent
if (!target || !event || state.pendingReports <= 0) {
state.drainScheduled = false
return
}

const reportsToDispatch = Math.min(reportsThisFrame, state.pendingReports)
for (let i = 0; i < reportsToDispatch; i++) {
target.dispatchEvent(cloneWheelReportEvent(event))
}
state.pendingReports -= reportsToDispatch

if (state.pendingReports <= 0) {
state.drainScheduled = false
state.pendingDirection = 0
state.pendingEvent = null
state.pendingTarget = null
return
}

scheduleWheelReplayFrame(() => {
drainTerminalTuiWheelReports(state, scheduleWheelReplayFrame, TUI_WHEEL_REPORTS_PER_FRAME)
})
}

function queueTerminalTuiWheelReports(
state: TerminalTuiMouseWheelReplayState,
target: EventTarget,
event: WheelEvent,
reportCount: number,
scheduleWheelReplayFrame: (callback: () => void) => void
): void {
const direction = wheelDirection(event)
if (state.pendingDirection !== 0 && state.pendingDirection !== direction) {
state.pendingReports = 0
}

state.pendingDirection = direction
state.pendingEvent = event
state.pendingTarget = target
state.pendingReports += reportCount

if (state.drainScheduled) {
return
}

state.drainScheduled = true
// Why: the first report should land immediately, while larger accelerated
// batches are paced across frames so fast scrolling does not feel bursty.
queueMicrotask(() => {
drainTerminalTuiWheelReports(state, scheduleWheelReplayFrame, 1)
})
}

export function attachTerminalMouseWheelMultiplier(
terminal: TerminalWheelTarget,
options: TerminalMouseWheelMultiplierOptions = {}
): void {
const replayState = createTerminalTuiMouseWheelReplayState()
terminal.attachCustomWheelEventHandler((event) => {
if (!shouldMultiplyTerminalMouseWheel(event, terminal.element)) {
return true
Expand All @@ -134,14 +283,18 @@ export function attachTerminalMouseWheelMultiplier(

// Why: xterm dampens small pixel deltas before emitting mouse reports;
// line-mode replays make each notched wheel tick produce immediate reports.
queueMicrotask(() => {
const multiplier = normalizeTerminalTuiMouseWheelMultiplier(
options.getTuiMouseWheelMultiplier?.()
)
for (let i = 0; i < multiplier; i++) {
target.dispatchEvent(cloneWheelReportEvent(event))
}
})
const reportCount = resolveTerminalTuiMouseWheelReportCount(
event,
normalizeTerminalTuiMouseWheelMultiplier(options.getTuiMouseWheelMultiplier?.()),
replayState.acceleration
)
queueTerminalTuiWheelReports(
replayState,
target,
event,
reportCount,
options.scheduleWheelReplayFrame ?? defaultScheduleWheelReplayFrame
)

return false
})
Expand Down
Loading
Loading