Debian Codegraph @

html_renderer/src/components/TimelineCanvasView.ts

raw symbols SCIP
1 import CanvasView from "../lib/CanvasView";
2 import type Frame from "../lib/model/Frame";
3 import { SELF_TIME_FRAME_IDENTIFIER } from "../lib/model/Frame";
4 import { hash, map, parseColor, sampleGradient } from "../lib/utils";
5 import TimelineCanvasViewTooltip, { estimateWidth, type TooltipFrameInfo } from "./TimelineCanvasViewTooltip.svelte";
6 import type { ComponentProps } from 'svelte';
7
8 const BACKGROUND_COLOR = '#212325'
9
10 const FRAME_PITCH = 18
11 const FRAME_HEIGHT = 17
12
13 const X_MARGIN = 28
14 const Y_MARGIN = 17
15 const Y_FRAME_INSET = 29 // vertical space between y margin and first frame, where the axis markers are drawn
16
17 const GRADIENT_STR = ['#3475BA','#318DBC','#47A298','#8AAE5D','#C1A731','#C07210','#B84210','#B53134','#9A3586','#4958B5','#3475BA']
18 const GRADIENT = GRADIENT_STR.map(parseColor)
19
20 export interface TimelineFrame {
21 frame: Frame
22 depth: number
23 // also cache some computed properties that are used in rendering
24 isApplicationCode: boolean
25 library: string | null
26 className: string
27 filePathShort: string | null
28 }
29 export default class TimelineCanvasView extends CanvasView {
30 zoom: number = 1 // pixels per second
31 startT: number = 0 // seconds
32 yOffset: number = 0 // pixels
33 frames: TimelineFrame[] = []
34 isZoomedIn: boolean = false
35
36 tooltipContainer: HTMLElement
37 tooltipComponent: TimelineCanvasViewTooltip | null = null
38
39 constructor(container: HTMLElement) {
40 super(container)
41
42 this.onWheel = this.onWheel.bind(this)
43 this.onMouseMove = this.onMouseMove.bind(this)
44 this.onMouseLeave = this.onMouseLeave.bind(this)
45 this.onMouseDown = this.onMouseDown.bind(this)
46 this.windowMouseUp = this.windowMouseUp.bind(this)
47 this.onTouchstart = this.onTouchstart.bind(this)
48 this.onTouchmove = this.onTouchmove.bind(this)
49 this.onTouchend = this.onTouchend.bind(this)
50 this.onTouchcancel = this.onTouchend.bind(this)
51 this.canvas.addEventListener('wheel', this.onWheel)
52 this.canvas.addEventListener('mousemove', this.onMouseMove)
53 this.canvas.addEventListener('mouseleave', this.onMouseLeave)
54 this.canvas.addEventListener('mousedown', this.onMouseDown)
55 this.canvas.addEventListener('touchstart', this.onTouchstart)
56 this.canvas.addEventListener('touchmove', this.onTouchmove)
57 this.canvas.addEventListener('touchend', this.onTouchend)
58 this.canvas.addEventListener('touchcancel', this.onTouchcancel)
59
60 this.tooltipContainer = document.createElement('div')
61 this.tooltipContainer.style.position = 'absolute'
62 this.tooltipContainer.style.pointerEvents = 'none'
63 this.container.appendChild(this.tooltipContainer)
64 }
65 destroy(): void {
66 this.canvas.removeEventListener('wheel', this.onWheel)
67 this.canvas.removeEventListener('mousemove', this.onMouseMove)
68 this.canvas.removeEventListener('mouseleave', this.onMouseLeave)
69 this.canvas.removeEventListener('mousedown', this.onMouseDown)
70 this.canvas.removeEventListener('touchstart', this.onTouchstart)
71 this.canvas.removeEventListener('touchmove', this.onTouchmove)
72 this.canvas.removeEventListener('touchend', this.onTouchend)
73 this.canvas.removeEventListener('touchcancel', this.onTouchcancel)
74 this.tooltipContainer.remove()
75 super.destroy()
76 }
77
78 _rootFrame: Frame | null = null
79 maxDepth = 0
80 setRootFrame(rootFrame: Frame) {
81 this._rootFrame = rootFrame
82 this.frames = []
83 this._frameMaxT = undefined
84 this.maxDepth = 0
85 this._collectFrames(rootFrame, 0)
86 this.fitContents()
87 this.setNeedsRedraw()
88 }
89
90 _collectFrames(frame: Frame, depth: number) {
91 this.frames.push({
92 frame,
93 depth,
94 isApplicationCode: frame.isApplicationCode,
95 library: frame.library,
96 className: frame.className,
97 filePathShort: frame.filePathShort,
98 })
99 this.maxDepth = Math.max(this.maxDepth, depth)
100 for (const child of frame.children) {
101 if (child.identifier !== SELF_TIME_FRAME_IDENTIFIER) {
102 // we don't render self time frames
103 this._collectFrames(child, depth + 1)
104 }
105 }
106 }
107
108 tooltipLocation: { x: number; y: number } | null = null
109
110 updateTooltip(ctx: CanvasRenderingContext2D, timelineFrame: TimelineFrame | null) {
111 // update the content
112 if (timelineFrame) {
113 const frameInfo: TooltipFrameInfo = {
114 name: this.frameName(timelineFrame),
115 time: timelineFrame.frame.time,
116 selfTime: this.frameSelfTime(timelineFrame),
117 totalTime: this._rootFrame?.time ?? 1e-12,
118 precision: this._rootFrame?.context.precision ?? 3,
119 location: `${timelineFrame.filePathShort}:${timelineFrame.frame.lineNo}`,
120 locationColor: this.colorForFrame(timelineFrame),
121 }
122
123 if (!this.tooltipComponent) {
124 this.tooltipComponent = new TimelineCanvasViewTooltip({
125 target: this.tooltipContainer,
126 props: {f: frameInfo},
127 })
128 } else {
129 this.tooltipComponent.$set({f: frameInfo})
130 }
131
132 // update the position
133 if (this.tooltipLocation) {
134 const position = {x: this.tooltipLocation.x + 12, y: this.tooltipLocation.y + 12}
135
136 // rather than reading the width from the DOM, we estimate it
137 // using canvas APIs. this tends to result in faster and more
138 // predictable results. Also the DOM is very inefficient at
139 // getting the size of something - it often has to relayout
140 // the entire page.
141 const tooltipWidth = estimateWidth(ctx, frameInfo)
142 const maxX = this.width - 10 - tooltipWidth
143 if (position.x > maxX) {
144 position.x = maxX
145 }
146 // note, this is a guess, but clipping off bottom will be rare, as will be wrapping tooltips
147 const tooltipHeight = 60
148 const maxY = this.height - 10 - tooltipHeight
149 if (position.y > maxY) {
150 position.y = maxY
151 }
152
153 this.tooltipContainer.style.left = `${position.x}px`
154 this.tooltipContainer.style.top = `${position.y}px`
155 }
156 }
157
158 if (!timelineFrame) {
159 if (this.tooltipComponent) {
160 this.tooltipComponent.$destroy()
161 this.tooltipComponent = null
162 }
163 }
164 }
165
166 // /$$$$$$$ /$$
167 // | $$__ $$ |__/
168 // | $$ \ $$ /$$$$$$ /$$$$$$ /$$ /$$ /$$ /$$ /$$$$$$$ /$$$$$$
169 // | $$ | $$ /$$__ $$ |____ $$| $$ | $$ | $$| $$| $$__ $$ /$$__ $$
170 // | $$ | $$| $$ \__/ /$$$$$$$| $$ | $$ | $$| $$| $$ \ $$| $$ \ $$
171 // | $$ | $$| $$ /$$__ $$| $$ | $$ | $$| $$| $$ | $$| $$ | $$
172 // | $$$$$$$/| $$ | $$$$$$$| $$$$$/$$$$/| $$| $$ | $$| $$$$$$$
173 // |_______/ |__/ \_______/ \_____/\___/ |__/|__/ |__/ \____ $$
174 // /$$ \ $$
175 // | $$$$$$/
176 // \______/
177
178 lastDrawWidth: number = 0
179 lastDrawHeight: number = 0
180
181 redraw(ctx: CanvasRenderingContext2D, extra: { width: number; height: number; }): void {
182 const { width, height } = extra
183
184 if (width !== this.lastDrawWidth || height !== this.lastDrawHeight) {
185 if (!this.isZoomedIn) {
186 this.fitContents()
187 } else {
188 this.clampViewport()
189 }
190 }
191 this.lastDrawWidth = width
192 this.lastDrawHeight = height
193
194 ctx.fillStyle = BACKGROUND_COLOR
195 ctx.fillRect(0, 0, width, height)
196
197 // draw scale
198 this.drawAxes(ctx)
199
200 // draw frames
201 for (const frame of this.frames) {
202 this.drawFrame(ctx, frame)
203 }
204
205 ctx.globalAlpha = 1
206
207 const canDrag = this.maxYOffset > 0 || this.isZoomedIn
208 const mouseDown = !!this.mouseDownLocation
209 this.canvas.style.cursor = (mouseDown && canDrag) ? 'grabbing' : 'initial'
210
211 // debug
212 ctx.fillStyle = 'red'
213 ctx.font = `23px "Source Sans Pro", sans-serif`
214 // ctx.fillText(`startT: ${this.startT}`, 10, 10)
215 // ctx.fillText(`zoom: ${this.zoom}`, 10, 50)
216 // ctx.fillText(`width/zoom: ${this.width / this.zoom}`, 10, 50)
217
218 let hoverFrame: TimelineFrame | null = null
219 if (!mouseDown && this.tooltipLocation) {
220 hoverFrame = this.hitTest(this.tooltipLocation)
221 }
222 this.updateTooltip(ctx, hoverFrame)
223 }
224
225 drawAxes(ctx: CanvasRenderingContext2D) {
226 // const viewportDuration = this.width / this.zoom
227 // clamp the width here to min 800 px, so that we don't draw too many
228 // axes on small screens
229 const viewportDuration = Math.max(800, this.width) / this.zoom
230
231 if (viewportDuration == 0) {
232 // avoid log of 0
233 return
234 }
235 const axisScale = Math.log10(viewportDuration)
236 let highestAxis = Math.ceil(axisScale) + 2
237 if (highestAxis < 0) {
238 // ensures that we always draw whole number axes, stops numbers
239 // like '0' from changing precision to '0.0' as we zoom in
240 highestAxis = 0
241 }
242 const smallestAxis = Math.ceil(axisScale) - 3
243 const alphaForAxis = (a: number) => map(a, {from: [axisScale, axisScale-3], to: [0.71, 0], clamp: true})
244 for (let a = smallestAxis; a < highestAxis; a++) {
245 let alpha = alphaForAxis(a)
246 alpha = Math.max(0, Math.min(1, alpha))
247 alpha = Math.pow(alpha, 2)
248 this.drawAxis(ctx, Math.pow(10, a), alpha)
249 }
250 // highest axis - set the flag to never skip as there are no higher increments
251 this.drawAxis(ctx, Math.pow(10, highestAxis), alphaForAxis(highestAxis), true)
252 }
253
254 drawAxis(ctx: CanvasRenderingContext2D, increment: number, alpha: number, dontSkip: boolean = false) {
255 ctx.fillStyle = 'white'
256 const startT = Math.floor(this.startT / increment) * increment
257 const endT = this.startT + this.width / this.zoom
258 const numDecimals = Math.max(0, Math.ceil(-Math.log10(increment)))
259
260 for (let t = startT; t < endT; t += increment) {
261 const x = this.xForT(t)
262 const drawnByAHigherIncrement = Math.round(t / increment) % 10 === 0
263 if (drawnByAHigherIncrement && !dontSkip) {
264 continue
265 }
266 ctx.globalAlpha = alpha
267 const y = Y_MARGIN - this.yOffset
268 ctx.fillRect(x, y, 1, this.height - y)
269
270 const textAlpha = map(alpha, {from: [0.12, 0.25], to: [0, 0.5], clamp: true})
271 if (textAlpha > 0.01) {
272 ctx.globalAlpha = textAlpha
273 ctx.font = `13px "Source Sans Pro", sans-serif`
274 let text = t.toFixed(numDecimals)
275 if (text == '0') {
276 text = '0s'
277 }
278 let topY = y + 10
279 ctx.fillText(text, x + 3, topY)
280 let bottomY = this.height + Y_MARGIN + 10 - this.yOffset
281 if (bottomY < this.height - 3) {
282 bottomY = this.height - 3
283 }
284 ctx.fillText(text, x + 3, bottomY)
285 }
286 ctx.globalAlpha = 1
287 }
288 }
289
290 drawFrame(ctx: CanvasRenderingContext2D, timelineFrame: TimelineFrame) {
291 const { x, y, w, h } = this.frameDims(timelineFrame)
292 const endX = x + w
293 if (endX < 0 || x > this.width) {
294 // offscreen
295 return
296 }
297
298 ctx.fillStyle = this.colorForFrame(timelineFrame)
299 ctx.globalAlpha = timelineFrame.isApplicationCode ? 1 : 0.5
300
301 if (w < 2) {
302 // fast path
303 ctx.fillRect(x, y, w, h)
304 return
305 }
306
307 let name = this.frameName(timelineFrame)
308
309 // the minimum width per character is 3.3px (that's an 'l')
310 // no point in drawing more characters than that, it'll be clipped
311 const maxChars = Math.floor(w / 3.3)
312 if (name.length > maxChars) {
313 name = name.substring(0, maxChars)
314 }
315 if (name.length == 0) {
316 // fast path
317 ctx.fillRect(x, y, w, h)
318 return
319 }
320
321 ctx.save()
322 ctx.beginPath()
323 ctx.rect(x, y, w, h)
324 ctx.fill()
325 ctx.clip()
326
327 ctx.font = `13px "Source Sans Pro", sans-serif`
328 ctx.fillStyle = 'white'
329 let textX = x
330 if (textX < 0) {
331 textX = 0
332 }
333 ctx.fillText(name, textX + 2, y + 13)
334
335 ctx.restore()
336 }
337
338 // the library order controls which color is assigned. More common
339 // libraries get colors further apart from each other
340 _libraryOrder: string[] | null = null
341 _assignLibraryOrder() {
342 const librariesTotalTime: Record<string, number> = {}
343
344 for (const timelineFrame of this.frames) {
345 const frame = timelineFrame.frame
346 const library = frame.library ?? ''
347 librariesTotalTime[library] = (librariesTotalTime[library] || 0) + timelineFrame.frame.time
348 }
349
350 const libraries = Object.keys(librariesTotalTime)
351 libraries.sort((a, b) => librariesTotalTime[b] - librariesTotalTime[a])
352 this._libraryOrder = libraries
353 }
354
355 _colors: string[] = []
356 colorForLibraryIndex(libraryIndex: number) {
357 if (this._colors[libraryIndex] !== undefined) {
358 return this._colors[libraryIndex]
359 }
360 // assign colors using color gradient and library order, gradually
361 // bisecting a color wheel - this gives the top libraries the most
362 // distinct colors
363 const denominator = Math.pow(2,Math.ceil(Math.log2(libraryIndex+1)))
364 const numerator = 2*libraryIndex - denominator + 1
365 const gradientLocation = numerator/denominator
366 const result = sampleGradient(GRADIENT, gradientLocation)
367 this._colors[libraryIndex] = result
368 return result
369 }
370
371 libraryIndexForFrame(timelineFrame: TimelineFrame) {
372 if (!this._libraryOrder) {
373 this._assignLibraryOrder()
374 }
375
376 const library = timelineFrame.library || ''
377 let result = this._libraryOrder!.indexOf(library)
378
379 if (result === -1) {
380 // we haven't seen this one before, add it to the list to give it an index
381 result = this._libraryOrder!.length
382 this._libraryOrder!.push(library)
383 }
384
385 return result
386 }
387
388 colorForFrame(timelineFrame: TimelineFrame) {
389 const libraryIndex = this.libraryIndexForFrame(timelineFrame)
390 const color = this.colorForLibraryIndex(libraryIndex)
391 return color
392 }
393
394 // /$$ /$$
395 // | $$ | $$
396 // | $$ /$$$$$$ /$$ /$$ /$$$$$$ /$$ /$$ /$$$$$$
397 // | $$ |____ $$| $$ | $$ /$$__ $$| $$ | $$|_ $$_/
398 // | $$ /$$$$$$$| $$ | $$| $$ \ $$| $$ | $$ | $$
399 // | $$ /$$__ $$| $$ | $$| $$ | $$| $$ | $$ | $$ /$$
400 // | $$$$$$$$| $$$$$$$| $$$$$$$| $$$$$$/| $$$$$$/ | $$$$/
401 // |________/ \_______/ \____ $$ \______/ \______/ \___/
402 // /$$ | $$
403 // | $$$$$$/
404 // \______/
405
406 _frameMaxT: number|undefined
407 get frameMaxT() {
408 if (this._frameMaxT === undefined) {
409 this._frameMaxT = this.frames.reduce((max, frame) => Math.max(max, frame.frame.startTime + frame.frame.time), 0)
410 }
411 return this._frameMaxT
412 }
413
414 get maxYOffset() {
415 return Math.max(0, (this.maxDepth+1) * FRAME_PITCH + Y_MARGIN*2 + Y_FRAME_INSET - this.height)
416 }
417
418 get minZoom() {
419 return (this.width - 2*X_MARGIN) / this.frameMaxT
420 }
421
422 get maxZoom() {
423 // 150 ns is the python function calling overhead.
424 // 150 ns per 10 pixels seems the smallest that makes sense to me
425 return 10 / 150e-9
426 }
427
428 fitContents() {
429 this.startT = 0
430 this.zoom = this.minZoom
431 this.isZoomedIn = false
432 }
433
434 clampViewport() {
435 if (this.zoom < this.minZoom) {
436 this.zoom = this.minZoom
437 this.isZoomedIn = false
438 } else {
439 this.isZoomedIn = true
440 }
441
442 if (this.zoom > this.maxZoom) {
443 this.zoom = this.maxZoom
444 }
445
446 if (this.startT < 0) {
447 this.startT = 0
448 }
449 const maxStartT = this.frameMaxT - (this.width - 2*X_MARGIN) / this.zoom
450 if (this.startT > maxStartT) {
451 this.startT = maxStartT
452 }
453
454 if (this.yOffset < 0) {
455 this.yOffset = 0
456 }
457 if (this.yOffset > this.maxYOffset) {
458 this.yOffset = this.maxYOffset
459 }
460 }
461
462 frameDims(timelineFrame: TimelineFrame): { x: number; y: number; w: number; h: number } {
463 const y = timelineFrame.depth * FRAME_PITCH + Y_MARGIN + Y_FRAME_INSET - this.yOffset
464 const h = FRAME_HEIGHT
465 let x = this.xForT(timelineFrame.frame.startTime)
466 const endX = this.xForT(timelineFrame.frame.startTime + timelineFrame.frame.time)
467 let w = endX - x
468
469 if (w < 1) {
470 w = 1
471 }
472 if (w > 1) {
473 // add a little gap between frames
474 w -= map(w, {from: [1,3], to: [0, 1], clamp: true})
475 }
476 return { x, y, w, h }
477 }
478
479 xForT(t: number): number {
480 return (t - this.startT) * this.zoom + X_MARGIN
481 }
482
483 tForX(x: number): number {
484 return (x - X_MARGIN) / this.zoom + this.startT
485 }
486
487 frameName(timelineFrame: TimelineFrame): string {
488 let name: string
489 if (timelineFrame.className) {
490 name = `${timelineFrame.className}.${timelineFrame.frame.function}`
491 } else if (timelineFrame.frame.function == '<module>'){
492 name = timelineFrame.filePathShort ?? timelineFrame.frame.filePath ?? ''
493 } else {
494 name = timelineFrame.frame.function
495 }
496 return name
497 }
498
499 frameSelfTime(timelineFrame: TimelineFrame): number {
500 let selfTime = timelineFrame.frame.time;
501 const renderedChildren = timelineFrame.frame.children.filter(child => !child.isSynthetic);
502
503 for (const child of renderedChildren) {
504 selfTime -= child.time;
505 }
506
507 return selfTime;
508 }
509
510 hitTest(loc: {x: number, y: number}): TimelineFrame | null {
511 for (const frame of this.frames) {
512 const { x: frameX, y: frameY, w, h } = this.frameDims(frame)
513 if (loc.x >= frameX && loc.x <= frameX + w && loc.y >= frameY && loc.y <= frameY + h) {
514 return frame
515 }
516 }
517 return null
518 }
519
520 // /$$ /$$
521 // | $$$ /$$$
522 // | $$$$ /$$$$ /$$$$$$ /$$ /$$ /$$$$$$$ /$$$$$$
523 // | $$ $$/$$ $$ /$$__ $$| $$ | $$ /$$_____/ /$$__ $$
524 // | $$ $$$| $$| $$ \ $$| $$ | $$| $$$$$$ | $$$$$$$$
525 // | $$\ $ | $$| $$ | $$| $$ | $$ \____ $$| $$_____/
526 // | $$ \/ | $$| $$$$$$/| $$$$$$/ /$$$$$$$/| $$$$$$$
527 // |__/ |__/ \______/ \______/ |_______/ \_______/
528 //
529 //
530 //
531 onWheel(event: WheelEvent) {
532 const isPinchGestureOrCmdWheel = event.ctrlKey || event.metaKey
533
534 // zooming
535 const zoomSpeed = isPinchGestureOrCmdWheel ? 0.01 : 0.0023
536 const mouseT = this.tForX(event.offsetX)
537 this.zoom *= 1 - event.deltaY * zoomSpeed
538 // an extra clamp to clamp this.zoom before the startT is adjusted
539 this.clampViewport()
540 this.startT = mouseT - (event.offsetX - X_MARGIN) / this.zoom
541
542 // scroll to pan
543 if (!isPinchGestureOrCmdWheel) {
544 this.startT += event.deltaX / this.zoom
545 }
546 this.clampViewport()
547 this.setNeedsRedraw()
548 event.preventDefault()
549 }
550 mouseLocation: { x: number; y: number } | null = null
551 mouseDownLocation: { x: number; y: number } | null = null
552 onMouseMove(event: MouseEvent): void {
553 const mouseLocation = { x: event.offsetX, y: event.offsetY }
554 const prevMouseLocation = this.mouseLocation
555 this.mouseLocation = mouseLocation
556 if (prevMouseLocation && this.mouseDownLocation) {
557 const dLocation = {x: mouseLocation.x - prevMouseLocation.x, y: mouseLocation.y - prevMouseLocation.y}
558 this.startT -= dLocation.x / this.zoom
559 this.yOffset -= dLocation.y
560 this.clampViewport()
561 }
562 this.tooltipLocation = mouseLocation
563 this.setNeedsRedraw()
564 }
565 onMouseLeave(event: MouseEvent): void {
566 this.mouseLocation = null
567 this.tooltipLocation = null
568 this.setNeedsRedraw()
569 }
570 onMouseDown(event: MouseEvent): void {
571 if (!(event.button === 0 || event.button === 1)) {
572 return
573 }
574 this.mouseDownLocation = { x: event.offsetX, y: event.offsetY }
575 window.addEventListener('mouseup', this.windowMouseUp)
576 this.setNeedsRedraw()
577 }
578 windowMouseUp(event: MouseEvent): void {
579 window.removeEventListener('mouseup', this.windowMouseUp)
580 this.mouseDownLocation = null
581 this.setNeedsRedraw()
582 }
583
584 // /$$$$$$$$ /$$
585 // |__ $$__/ | $$
586 // | $$ /$$$$$$ /$$ /$$ /$$$$$$$| $$$$$$$
587 // | $$ /$$__ $$| $$ | $$ /$$_____/| $$__ $$
588 // | $$ | $$ \ $$| $$ | $$| $$ | $$ \ $$
589 // | $$ | $$ | $$| $$ | $$| $$ | $$ | $$
590 // | $$ | $$$$$$/| $$$$$$/| $$$$$$$| $$ | $$
591 // |__/ \______/ \______/ \_______/|__/ |__/
592
593 touches: { [key: number]: { x: number; y: number, downT: number, startDate: number, downX: number, downY: number } } = {}
594 onTouchstart(event: TouchEvent) {
595 event.preventDefault()
596 event.stopPropagation()
597
598 for (const touch of Array.from(event.changedTouches)) {
599 this.touches[touch.identifier] = {
600 x: touch.clientX,
601 y: touch.clientY,
602 downT: this.tForX(touch.clientX),
603 startDate: Date.now(),
604 downX: touch.clientX,
605 downY: touch.clientY,
606 }
607 }
608 }
609 onTouchmove(event: TouchEvent) {
610 event.preventDefault()
611 event.stopPropagation()
612
613 let yMotionSum = 0
614 for (const touch of Array.from(event.changedTouches)) {
615 const prevTouch = this.touches[touch.identifier]
616 if (!prevTouch) {
617 continue
618 }
619 yMotionSum += touch.clientY - prevTouch.y
620 this.touches[touch.identifier] = {
621 ...prevTouch,
622 x: touch.clientX,
623 y: touch.clientY
624 }
625 }
626 const yMotion = yMotionSum / Object.keys(this.touches).length
627 this.yOffset -= yMotion
628 this.adjustXAxisForTouches()
629 this.setNeedsRedraw()
630 }
631 onTouchend(event: TouchEvent) {
632 event.preventDefault()
633 event.stopPropagation()
634
635 for (const touch of Array.from(event.changedTouches)) {
636 delete this.touches[touch.identifier]
637 }
638 this.setNeedsRedraw()
639 }
640 onTouchcancel(event: TouchEvent) {
641 event.preventDefault()
642 event.stopPropagation()
643
644 for (const touch of Array.from(event.changedTouches)) {
645 delete this.touches[touch.identifier]
646 }
647 this.setNeedsRedraw()
648 }
649 adjustXAxisForTouches() {
650 const touchIds = Object.keys(this.touches).map(Number)
651 if (touchIds.length == 0) {
652 return
653 }
654 if (touchIds.length == 1) {
655 const touch = this.touches[touchIds[0]]
656 this.startT = touch.downT - (touch.x - X_MARGIN) / this.zoom
657 }
658 if (touchIds.length >= 2) {
659 const touch1 = this.touches[touchIds[0]]
660 const touch2 = this.touches[touchIds[1]]
661 const newZoom = (touch2.x - touch1.x) / (touch2.downT - touch1.downT)
662 const newStartT = touch1.downT - (touch1.x - X_MARGIN) / newZoom
663 this.startT = newStartT
664 this.zoom = newZoom
665 }
666 this.clampViewport()
667 }
668 }