import {DOM} from '../../util/dom.ts'; import {defaultEasing, bezier, zoomScale, scaleZoom, evaluateZoomSnap} from '../../util/util.ts'; import {now} from '../../util/time_control.ts'; import {interpolates} from '@maplibre/maplibre-gl-style-spec'; import {getCameraMath} from '../../camera/camera_math_factory.ts'; import {applyConstrain} from '../../camera/camera_constrain.ts'; import type {Camera} from '../camera.ts'; import type {CooperativeGesturesHandler} from './cooperative_gestures.ts'; import type {AroundCenterOptions} from './two_fingers_touch.ts'; import type {Handler, HandlerResult} from '../handler_manager.ts'; import type Point from '@mapbox/point-geometry'; // deltaY value for mouse scroll wheel identification const wheelZoomDelta = 4.000244140625; // These magic numbers control the rate of zoom. Trackpad events fire at a greater // frequency than mouse scroll wheel, so reduce the zoom rate per wheel tick const defaultZoomRate = 1 / 100; const wheelZoomRate = 1 / 450; // upper bound on how much we scale the map in any single render frame; this // is used to limit zoom rate in the case of very fast scrolling const maxScalePerFrame = 2; // Minimum time difference value to be used for calculating zoom easing in renderFrame(); // this is used to normalise very fast (typically 0 to 0.3ms) repeating lastWheelEventTimeDiff // values generated by Chromium based browsers during fast scrolling wheel events. const wheelEventTimeDiffAdjustment = 5; /** * A wait scroll zoom asks the handler manager for, see {@link HandlerResult.timeout}. A `singleWheel` wait is for a * second wheel event, which tells a trackpad from a mouse wheel, whose ticks come further apart. A `finish` wait is * between a zoom reaching its target and its end events, so that a scroll right after continues the same zoom. */ type ScrollZoomWait = {reason: 'singleWheel'; event: WheelEvent} | {reason: 'finish'}; /** * The `ScrollZoomHandler` allows the user to zoom the map by scrolling. * * @group Handlers */ export class ScrollZoomHandler implements Handler { private _canvas: HTMLElement; private _cooperativeGestures: CooperativeGesturesHandler; private _camera: Camera; private _enabled: boolean; private _active: boolean; private _zooming: boolean; private _aroundCenter: boolean; private _aroundPoint: Point; private _type: 'wheel' | 'trackpad' | null; private _lastValue: number; /** The `singleWheel` wait in progress, if any; a wait that has been replaced or abandoned is ignored when it ends. */ private _singleWheelWait: ScrollZoomWait | undefined; /** The `finish` wait in progress, if any; a wait that has been replaced or abandoned is ignored when it ends. */ private _finishWait: ScrollZoomWait | undefined; private _lastWheelEvent: WheelEvent; private _lastWheelEventTime: number; private _lastExpectedZoom: number; private _startZoom: number; private _targetZoom: number; private _delta: number; private _easing: ((a: number) => number); private _prevEase: { start: number; duration: number; easing: (_: number) => number; }; private _needsRerender: boolean; private _defaultZoomRate: number; private _wheelZoomRate: number; /** @internal */ constructor(canvas: HTMLElement, cooperativeGestures: CooperativeGesturesHandler, camera: Camera) { this._canvas = canvas; this._cooperativeGestures = cooperativeGestures; this._camera = camera; this._delta = 0; this._defaultZoomRate = defaultZoomRate; this._wheelZoomRate = wheelZoomRate; } /** * Set the zoom rate of a trackpad * @param zoomRate - 1/100 The rate used to scale trackpad movement to a zoom value. * @example * Speed up trackpad zoom * ```ts * map.scrollZoom.setZoomRate(1/25); * ``` */ setZoomRate(zoomRate: number): void { this._defaultZoomRate = zoomRate; } /** * Set the zoom rate of a mouse wheel * @param wheelZoomRate - 1/450 The rate used to scale mouse wheel movement to a zoom value. * @example * Slow down zoom of mouse wheel * ```ts * map.scrollZoom.setWheelZoomRate(1/600); * ``` */ setWheelZoomRate(wheelZoomRate: number): void { this._wheelZoomRate = wheelZoomRate; } /** * Returns a Boolean indicating whether the "scroll to zoom" interaction is enabled. * @returns `true` if the "scroll to zoom" interaction is enabled. */ isEnabled(): boolean { return !!this._enabled; } /* * Active state is turned on and off with every scroll wheel event and is set back to false before the map * render is called, so _active is not a good candidate for determining if a scroll zoom animation is in * progress. */ isActive(): boolean { return !!this._active || this._finishWait !== undefined; } isZooming(): boolean { return !!this._zooming; } /** * Enables the "scroll to zoom" interaction. * * @param options - Options object. * @example * ```ts * map.scrollZoom.enable(); * map.scrollZoom.enable({ around: 'center' }) * ``` */ enable(options?: AroundCenterOptions | boolean): void { if (this.isEnabled()) return; this._enabled = true; this._aroundCenter = !!options && (options as AroundCenterOptions).around === 'center'; } /** * Disables the "scroll to zoom" interaction. * * @example * ```ts * map.scrollZoom.disable(); * ``` */ disable(): void { if (!this.isEnabled()) return; this._enabled = false; } /** * Determines whether or not the gesture is blocked due to cooperativeGestures. */ private _shouldBePrevented(e: WheelEvent): boolean { if (!this._cooperativeGestures.isEnabled()) { return false; } const isTrackpadPinch = e.ctrlKey; const isBypassed = isTrackpadPinch || this._cooperativeGestures.isBypassed(e); return !isBypassed; } wheel(e: WheelEvent): HandlerResult | void { if (!this.isEnabled()) return; if (this._shouldBePrevented(e)) { this._cooperativeGestures.notifyGestureBlocked('wheel_zoom', e); return; } let value = e.deltaMode === WheelEvent.DOM_DELTA_LINE ? e.deltaY * 40 : e.deltaY; let result: HandlerResult | void; const currentTime = now(), timeDelta = currentTime - (this._lastWheelEventTime || 0); this._lastWheelEventTime = currentTime; if (value !== 0 && (value % wheelZoomDelta) === 0) { // This one is definitely a mouse wheel event. this._type = 'wheel'; } else if (value !== 0 && Math.abs(value) < 4) { // This one is definitely a trackpad event because it is so small. this._type = 'trackpad'; } else if (timeDelta > 400) { // This is likely a new scroll action. this._type = null; this._lastValue = value; // Wait up to 40ms in case this was a singular event. this._singleWheelWait = {reason: 'singleWheel', event: e}; result = {timeout: {delay: 40, token: this._singleWheelWait}}; } else if (!this._type) { // This is a repeating event, but we don't know the type of event just yet. // If the delta per time is small, we assume it's a fast trackpad; otherwise we switch into wheel mode. this._type = (Math.abs(timeDelta * value) < 200) ? 'trackpad' : 'wheel'; // Stop waiting on the previous event (which was less than 40ms ago), because we accumulate it into this event. if (this._singleWheelWait) { this._singleWheelWait = undefined; value += this._lastValue; } } // Slow down zoom if shift key is held for more precise zooming if (e.shiftKey && value) value = value / 4; // Only fire the callback if we actually know what type of scrolling device the user uses. if (this._type) { this._lastWheelEvent = e; this._delta -= value; if (!this._active) { result = this._start(e); } } e.preventDefault(); return result; } /** * @internal * Ends a wait the handler asked the manager for, see {@link HandlerResult.timeout}: a single wheel event that no * second one followed is a mouse wheel's, and a zoom that no further scroll continued ends. A wait the handler no * longer waits for, because a later scroll replaced it, is ignored. */ onTimeout(wait: ScrollZoomWait): HandlerResult | void { if (wait !== this._singleWheelWait && wait !== this._finishWait) return; switch (wait.reason) { case 'singleWheel': this._singleWheelWait = undefined; this._type = 'wheel'; this._delta -= this._lastValue; if (!this._active) return this._start(wait.event); return; case 'finish': this._zooming = false; delete this._targetZoom; delete this._lastExpectedZoom; delete this._finishWait; return {needsRenderFrame: true}; } } private _start(e: MouseEvent): HandlerResult | void { if (!this._delta) return; this._needsRerender = false; this._active = true; if (!this.isZooming()) { this._zooming = true; } delete this._finishWait; const pos = DOM.mousePos(this._canvas, e); // Whether aroundPoint is actually unprojectable is not a problem to be solved here, but in handler_manager.ts instead. if (this._aroundCenter) { const projectedCamera = this._camera.proposedProjectedCamera; this._aroundPoint = getCameraMath(projectedCamera).locationToScreenPoint(projectedCamera, this._camera.context.worldCoordinateHelper, projectedCamera.center); } else { this._aroundPoint = pos; } if (!this._needsRerender) { this._needsRerender = true; return {needsRenderFrame: true}; } } renderFrame(): HandlerResult | void { if (!this._needsRerender) return; this._needsRerender = false; if (!this.isActive()) return; const projectedCamera = this._camera.proposedProjectedCamera; // When globe is enabled zoom might be modified by the map center latitude being changes (either by panning or by zoom moving the map) if (typeof this._lastExpectedZoom === 'number') { const externalZoomChange = projectedCamera.zoom - this._lastExpectedZoom; if (typeof this._startZoom === 'number') { this._startZoom += externalZoomChange; } if (typeof this._targetZoom === 'number') { this._targetZoom += externalZoomChange; } } // if we've had scroll events since the last render frame, consume the // accumulated delta, and update the target zoom level accordingly if (this._delta !== 0) { // For trackpad events and single mouse wheel ticks, use the default zoom rate const zoomRate = (this._type === 'wheel' && Math.abs(this._delta) > wheelZoomDelta) ? this._wheelZoomRate : this._defaultZoomRate; // Scale by sigmoid of scroll wheel delta so the map responds to small scrolls and compresses large scrolls let scale = maxScalePerFrame / (1 + Math.exp(-Math.abs(this._delta * zoomRate))); if (this._delta < 0 && scale !== 0) { scale = 1 / scale; } const fromScale = typeof this._targetZoom !== 'number' ? projectedCamera.scale : zoomScale(this._targetZoom); const cameraLngLat = getCameraMath(projectedCamera).getCameraLngLat(projectedCamera, this._camera.context.worldCoordinateHelper); const target = applyConstrain(this._camera.renderedState, this._camera.context, cameraLngLat, scaleZoom(fromScale * scale)).zoom; const zoomSnap = this._camera.getZoomSnap(); if (this._type === 'wheel' && zoomSnap > 0) { const currentSnapped = evaluateZoomSnap(projectedCamera.zoom, zoomSnap); this._targetZoom = evaluateZoomSnap(target, zoomSnap, target - currentSnapped); } else { this._targetZoom = target; } // if this is a mouse wheel, refresh the starting zoom and easing // function we're using to smooth out the zooming between wheel // events if (this._type === 'wheel') { this._startZoom = projectedCamera.zoom; this._easing = this._smoothOutEasing(200); } this._delta = 0; } const targetZoom = typeof this._targetZoom !== 'number' ? projectedCamera.zoom : this._targetZoom; const startZoom = this._startZoom; const easing = this._easing; let finished = false; let zoom; if (this._type === 'wheel' && startZoom && easing) { const lastWheelEventTimeDiff = now() - this._lastWheelEventTime; const t = Math.min((lastWheelEventTimeDiff + wheelEventTimeDiffAdjustment) / 200, 1); const k = easing(t); zoom = interpolates.number(startZoom, targetZoom, k); if (t < 1) { this._needsRerender = true; } else { finished = true; } } else { zoom = targetZoom; finished = true; } this._active = true; if (finished) { this._active = false; this._finishWait = {reason: 'finish'}; } this._lastExpectedZoom = zoom; return { noInertia: true, needsRenderFrame: !finished, zoomDelta: zoom - projectedCamera.zoom, around: this._aroundPoint, originalEvent: this._lastWheelEvent, timeout: finished ? {delay: 200, token: this._finishWait} : undefined }; } private _smoothOutEasing(duration: number): (t: number) => number { let easing = defaultEasing; if (this._prevEase) { const currentEase = this._prevEase; const t = (now() - currentEase.start) / currentEase.duration; const speed = currentEase.easing(t + 0.01) - currentEase.easing(t); // Quick hack to make new bezier that is continuous with last const x = 0.27 / Math.sqrt(speed * speed + 0.0001) * 0.01; const y = Math.sqrt(0.27 * 0.27 - x * x); easing = bezier(x, y, 0.25, 1); } this._prevEase = { start: now(), duration, easing }; return easing; } reset(): void { this._active = false; this._zooming = false; delete this._targetZoom; delete this._lastExpectedZoom; delete this._finishWait; } }