timeline-track-base.mjs 17.9 KB
Newer Older
1 2 3 4 5
// Copyright 2020 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import {delay} from '../../helper.mjs';
6
import {kChunkHeight, kChunkVisualWidth, kChunkWidth} from '../../log/map.mjs';
7 8 9
import {SelectionEvent, SelectTimeEvent, SynchronizeSelectionEvent, ToolTipEvent,} from '../events.mjs';
import {CSSColor, DOM, SVG, V8CustomElement} from '../helper.mjs';

10 11
export const kTimelineHeight = 200;

12 13 14
export class TimelineTrackBase extends V8CustomElement {
  _timeline;
  _nofChunks = 500;
15
  _chunks = [];
16
  _selectedEntry;
17
  _focusedEntry;
18
  _timeToPixel;
19
  _timeStartPixelOffset;
20
  _legend;
21
  _lastContentWidth = 0;
22

23 24 25
  _cachedTimelineBoundingClientRect;
  _cachedTimelineScrollLeft;

26 27 28 29 30
  constructor(templateText) {
    super(templateText);
    this._selectionHandler = new SelectionHandler(this);
    this._legend = new Legend(this.$('#legendTable'));
    this._legend.onFilter = (type) => this._handleFilterTimeline();
31 32 33 34 35 36 37 38 39 40

    this.timelineChunks = this.$('#timelineChunks');
    this.timelineSamples = this.$('#timelineSamples');
    this.timelineNode = this.$('#timeline');
    this.toolTipTargetNode = this.$('#toolTipTarget');
    this.hitPanelNode = this.$('#hitPanel');
    this.timelineAnnotationsNode = this.$('#timelineAnnotations');
    this.timelineMarkersNode = this.$('#timelineMarkers');
    this._scalableContentNode = this.$('#scalableContent');

41 42
    this.timelineNode.addEventListener(
        'scroll', e => this._handleTimelineScroll(e));
43 44 45 46
    this.hitPanelNode.onclick = this._handleClick.bind(this);
    this.hitPanelNode.ondblclick = this._handleDoubleClick.bind(this);
    this.hitPanelNode.onmousemove = this._handleMouseMove.bind(this);
    window.addEventListener('resize', () => this._resetCachedDimensions());
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
    this.isLocked = false;
  }

  static get observedAttributes() {
    return ['title'];
  }

  attributeChangedCallback(name, oldValue, newValue) {
    if (name == 'title') {
      this.$('#title').innerHTML = newValue;
    }
  }

  _handleFilterTimeline(type) {
    this._updateChunks();
  }

  set data(timeline) {
    this._timeline = timeline;
    this._legend.timeline = timeline;
    this.$('.content').style.display = timeline.isEmpty() ? 'none' : 'relative';
    this._updateChunks();
  }

  set timeSelection(selection) {
    this._selectionHandler.timeSelection = selection;
    this.updateSelection();
  }

  updateSelection() {
    this._selectionHandler.update();
    this._legend.update();
  }

81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
  get _timelineBoundingClientRect() {
    if (this._cachedTimelineBoundingClientRect === undefined) {
      this._cachedTimelineBoundingClientRect =
          this.timelineNode.getBoundingClientRect();
    }
    return this._cachedTimelineBoundingClientRect;
  }

  get _timelineScrollLeft() {
    if (this._cachedTimelineScrollLeft === undefined) {
      this._cachedTimelineScrollLeft = this.timelineNode.scrollLeft;
    }
    return this._cachedTimelineScrollLeft;
  }

  _resetCachedDimensions() {
    this._cachedTimelineBoundingClientRect = undefined;
    this._cachedTimelineScrollLeft = undefined;
  }

  // Maps the clicked x position to the x position on timeline
102
  positionOnTimeline(pagePosX) {
103 104
    let rect = this._timelineBoundingClientRect;
    let posClickedX = pagePosX - rect.left + this._timelineScrollLeft;
105 106 107 108
    return posClickedX;
  }

  positionToTime(pagePosX) {
109 110 111 112 113
    return this.relativePositionToTime(this.positionOnTimeline(pagePosX));
  }

  relativePositionToTime(timelineRelativeX) {
    const timelineAbsoluteX = timelineRelativeX + this._timeStartPixelOffset;
114
    return (timelineAbsoluteX / this._timeToPixel) | 0;
115 116 117 118
  }

  timeToPosition(time) {
    let relativePosX = time * this._timeToPixel;
119
    relativePosX -= this._timeStartPixelOffset;
120 121 122 123
    return relativePosX;
  }

  set nofChunks(count) {
124
    this._nofChunks = count | 0;
125 126 127 128 129 130 131 132
    this._updateChunks();
  }

  get nofChunks() {
    return this._nofChunks;
  }

  _updateChunks() {
133 134
    this._chunks = undefined;
    this._updateDimensions();
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
    this.requestUpdate();
  }

  get chunks() {
    return this._chunks;
  }

  set selectedEntry(value) {
    this._selectedEntry = value;
    this.drawAnnotations(value);
  }

  get selectedEntry() {
    return this._selectedEntry;
  }

  set scrollLeft(offset) {
    this.timelineNode.scrollLeft = offset;
153
    this._cachedTimelineScrollLeft = offset;
154 155 156 157 158 159 160 161
  }

  handleEntryTypeDoubleClick(e) {
    this.dispatchEvent(new SelectionEvent(e.target.parentNode.entries));
  }

  timelineIndicatorMove(offset) {
    this.timelineNode.scrollLeft += offset;
162
    this._cachedTimelineScrollLeft = undefined;
163 164 165
  }

  _handleTimelineScroll(e) {
166 167
    let scrollLeft = e.currentTarget.scrollLeft;
    this._cachedTimelineScrollLeft = scrollLeft;
168
    this.dispatchEvent(new CustomEvent(
169
        'scrolltrack', {bubbles: true, composed: true, detail: scrollLeft}));
170 171
  }

172
  _updateDimensions() {
173 174 175
    const centerOffset = this._timelineBoundingClientRect.width / 2;
    const time =
        this.relativePositionToTime(this._timelineScrollLeft + centerOffset);
176 177 178 179 180
    const start = this._timeline.startTime;
    const width = this._nofChunks * kChunkWidth;
    this._lastContentWidth = parseInt(this.timelineMarkersNode.style.width);
    this._timeToPixel = width / this._timeline.duration();
    this._timeStartPixelOffset = start * this._timeToPixel;
181 182 183
    this.timelineChunks.style.width = `${width}px`;
    this.timelineMarkersNode.style.width = `${width}px`;
    this.timelineAnnotationsNode.style.width = `${width}px`;
184
    this.hitPanelNode.style.width = `${width}px`;
185
    this._drawMarkers();
186 187
    this._selectionHandler.update();
    this._scaleContent(width);
188 189
    this._cachedTimelineScrollLeft = this.timelineNode.scrollLeft =
        this.timeToPosition(time) - centerOffset;
190 191 192 193 194 195 196 197
  }

  _scaleContent(currentWidth) {
    if (!this._lastContentWidth) return;
    const ratio = currentWidth / this._lastContentWidth;
    this._scalableContentNode.style.transform = `scale(${ratio}, 1)`;
  }

198
  _adjustHeight(height) {
199 200 201 202
    const dataHeight = Math.max(height, 200);
    const viewHeight = Math.min(dataHeight, 400);
    this.style.setProperty('--data-height', dataHeight + 'px');
    this.style.setProperty('--view-height', viewHeight + 'px');
203 204
    this.timelineNode.style.overflowY =
        (height > kTimelineHeight) ? 'scroll' : 'hidden';
205 206
  }

207 208
  _update() {
    this._legend.update();
209 210
    this._drawContent();
    this._drawAnnotations(this.selectedEntry);
211
    this._resetCachedDimensions();
212 213 214
  }

  async _drawContent() {
215
    await delay(5);
216
    if (this._timeline.isEmpty()) return;
217 218 219 220 221
    if (this.chunks?.length != this.nofChunks) {
      this._chunks =
          this._timeline.chunks(this.nofChunks, this._legend.filterPredicate);
      console.assert(this._chunks.length == this._nofChunks);
    }
222 223 224 225 226 227 228 229 230 231 232 233
    const chunks = this.chunks;
    const max = chunks.max(each => each.size());
    let buffer = '';
    for (let i = 0; i < chunks.length; i++) {
      const chunk = chunks[i];
      const height = (chunk.size() / max * kChunkHeight);
      chunk.height = height;
      if (chunk.isEmpty()) continue;
      buffer += '<g>';
      buffer += this._drawChunk(i, chunk);
      buffer += '</g>'
    }
234 235
    this._scalableContentNode.innerHTML = buffer;
    this._scalableContentNode.style.transform = 'scale(1, 1)';
236 237 238 239 240 241
  }

  _drawChunk(chunkIndex, chunk) {
    const groups = chunk.getBreakdown(event => event.type);
    let buffer = '';
    const kHeight = chunk.height;
242
    let lastHeight = kTimelineHeight;
243 244 245 246 247 248 249
    for (let i = 0; i < groups.length; i++) {
      const group = groups[i];
      if (group.count == 0) break;
      const height = (group.count / chunk.size() * kHeight) | 0;
      lastHeight -= height;
      const color = this._legend.colorForType(group.key);
      buffer += `<rect x=${chunkIndex * kChunkWidth} y=${lastHeight} height=${
250
          height} width=${kChunkVisualWidth} fill=${color} />`
251 252 253 254 255 256
    }
    return buffer;
  }

  _drawMarkers() {
    // Put a time marker roughly every 20 chunks.
257
    const expected = this._timeline.duration() / this._nofChunks * 20;
258 259 260 261 262 263 264
    let interval = (10 ** Math.floor(Math.log10(expected)));
    let correction = Math.log10(expected / interval);
    correction = (correction < 0.33) ? 1 : (correction < 0.75) ? 2.5 : 5;
    interval *= correction;

    const start = this._timeline.startTime;
    let time = start;
265
    let buffer = '';
266
    while (time < this._timeline.endTime) {
267 268 269 270 271 272
      const delta = time - start;
      const text = `${(delta / 1000) | 0} ms`;
      const x = (delta * this._timeToPixel) | 0;
      buffer += `<text x=${x - 2} y=0 class=markerText >${text}</text>`
      buffer +=
          `<line x1=${x} x2=${x} y1=12 y2=2000 dy=100% class=markerLine />`
273 274
      time += interval;
    }
275
    this.timelineMarkersNode.innerHTML = buffer;
276 277
  }

278
  _drawAnnotations(logEntry, time) {
279 280 281 282 283 284 285 286 287 288
    if (!this._focusedEntry) return;
    this._drawEntryMark(this._focusedEntry);
  }

  _drawEntryMark(entry) {
    const [x, y] = this._positionForEntry(entry);
    const color = this._legend.colorForType(entry.type);
    const mark =
        `<circle cx=${x} cy=${y} r=3 stroke=${color} class=annotationPoint />`;
    this.timelineAnnotationsNode.innerHTML = mark;
289 290
  }

291
  _handleUnlockedMouseEvent(event) {
292 293 294
    this._focusedEntry = this._getEntryForEvent(event);
    if (!this._focusedEntry) return false;
    this._updateToolTip(event);
295
    const time = this.positionToTime(event.pageX);
296 297 298 299 300 301 302
    this._drawAnnotations(this._focusedEntry, time);
  }

  _updateToolTip(event) {
    this.dispatchEvent(
        new ToolTipEvent(this._focusedEntry, this.toolTipTargetNode));
    event.stopImmediatePropagation();
303 304
  }

305
  _handleClick(event) {
306
    if (event.button !== 0) return;
307
    if (event.target === this.timelineChunks) return;
308
    this.isLocked = !this.isLocked;
309 310 311
    // Do this unconditionally since we want the tooltip to be update to the
    // latest locked state.
    this._handleUnlockedMouseEvent(event);
312
    return false;
313 314
  }

315
  _handleDoubleClick(event) {
316
    if (event.button !== 0) return;
317
    this._selectionHandler.clearSelection();
318 319
    const time = this.positionToTime(event.pageX);
    const chunk = this._getChunkForEvent(event)
320
    if (!chunk) return;
321
    event.stopImmediatePropagation();
322
    this.dispatchEvent(new SelectTimeEvent(chunk.start, chunk.end));
323 324 325 326
    return false;
  }

  _handleMouseMove(event) {
327
    if (event.button !== 0) return;
328
    if (this._selectionHandler.isSelecting) return false;
329
    if (this.isLocked && this._focusedEntry) {
330 331 332
      this._updateToolTip(event);
      return false;
    }
333
    this._handleUnlockedMouseEvent(event);
334 335
  }

336
  _getChunkForEvent(event) {
337
    const time = this.positionToTime(event.pageX);
338 339 340 341
    return this._chunkForTime(time);
  }

  _chunkForTime(time) {
342 343 344 345 346 347
    const chunkIndex = ((time - this._timeline.startTime) /
                        this._timeline.duration() * this._nofChunks) |
        0;
    return this.chunks[chunkIndex];
  }

348 349 350 351 352 353 354 355 356
  _positionForEntry(entry) {
    const chunk = this._chunkForTime(entry.time);
    if (chunk === undefined) return [-1, -1];
    const xFrom = (chunk.index * kChunkWidth + kChunkVisualWidth / 2) | 0;
    const yFrom = kTimelineHeight - chunk.yOffset(entry) | 0;
    console.log(xFrom, yFrom);
    return [xFrom, yFrom];
  }

357 358 359 360 361 362 363 364 365 366 367
  _getEntryForEvent(event) {
    const chunk = this._getChunkForEvent(event);
    if (chunk?.isEmpty() ?? true) return false;
    const relativeIndex = Math.round(
        (kTimelineHeight - event.layerY) / chunk.height * (chunk.size() - 1));
    if (relativeIndex > chunk.size()) return false;
    const logEntry = chunk.at(relativeIndex);
    const style = this.toolTipTargetNode.style;
    style.left = `${chunk.index * kChunkWidth}px`;
    style.top = `${kTimelineHeight - chunk.height}px`;
    style.height = `${chunk.height}px`;
368
    style.width = `${kChunkVisualWidth}px`;
369
    return logEntry;
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471
  }
};

class SelectionHandler {
  // TODO turn into static field once Safari supports it.
  static get SELECTION_OFFSET() {
    return 10
  };

  _timeSelection = {start: -1, end: Infinity};
  _selectionOriginTime = -1;

  constructor(timeline) {
    this._timeline = timeline;
    this._timelineNode.addEventListener(
        'mousedown', e => this._handleTimeSelectionMouseDown(e));
    this._timelineNode.addEventListener(
        'mouseup', e => this._handleTimeSelectionMouseUp(e));
    this._timelineNode.addEventListener(
        'mousemove', e => this._handleTimeSelectionMouseMove(e));
  }

  update() {
    if (!this.hasSelection) {
      this._selectionNode.style.display = 'none';
      return;
    }
    this._selectionNode.style.display = 'inherit';
    const startPosition = this.timeToPosition(this._timeSelection.start);
    const endPosition = this.timeToPosition(this._timeSelection.end);
    this._leftHandleNode.style.left = startPosition + 'px';
    this._rightHandleNode.style.left = endPosition + 'px';
    const delta = endPosition - startPosition;
    const selectionNode = this._selectionBackgroundNode;
    selectionNode.style.left = startPosition + 'px';
    selectionNode.style.width = delta + 'px';
  }

  set timeSelection(selection) {
    this._timeSelection.start = selection.start;
    this._timeSelection.end = selection.end;
  }

  clearSelection() {
    this._timeline.dispatchEvent(new SelectTimeEvent());
  }

  timeToPosition(posX) {
    return this._timeline.timeToPosition(posX);
  }

  positionToTime(posX) {
    return this._timeline.positionToTime(posX);
  }

  get isSelecting() {
    return this._selectionOriginTime >= 0;
  }

  get hasSelection() {
    return this._timeSelection.start >= 0 &&
        this._timeSelection.end != Infinity;
  }

  get _timelineNode() {
    return this._timeline.$('#timeline');
  }

  get _selectionNode() {
    return this._timeline.$('#selection');
  }

  get _selectionBackgroundNode() {
    return this._timeline.$('#selectionBackground');
  }

  get _leftHandleNode() {
    return this._timeline.$('#leftHandle');
  }

  get _rightHandleNode() {
    return this._timeline.$('#rightHandle');
  }

  get _leftHandlePosX() {
    return this._leftHandleNode.getBoundingClientRect().x;
  }

  get _rightHandlePosX() {
    return this._rightHandleNode.getBoundingClientRect().x;
  }

  _isOnLeftHandle(posX) {
    return Math.abs(this._leftHandlePosX - posX) <=
        SelectionHandler.SELECTION_OFFSET;
  }

  _isOnRightHandle(posX) {
    return Math.abs(this._rightHandlePosX - posX) <=
        SelectionHandler.SELECTION_OFFSET;
  }

472 473 474
  _handleTimeSelectionMouseDown(event) {
    if (event.button !== 0) return;
    let xPosition = event.clientX
475 476 477 478 479 480 481 482 483 484
    // Update origin time in case we click on a handle.
    if (this._isOnLeftHandle(xPosition)) {
      xPosition = this._rightHandlePosX;
    }
    else if (this._isOnRightHandle(xPosition)) {
      xPosition = this._leftHandlePosX;
    }
    this._selectionOriginTime = this.positionToTime(xPosition);
  }

485 486
  _handleTimeSelectionMouseMove(event) {
    if (event.button !== 0) return;
487
    if (!this.isSelecting) return;
488
    const currentTime = this.positionToTime(event.clientX);
489 490 491 492 493
    this._timeline.dispatchEvent(new SynchronizeSelectionEvent(
        Math.min(this._selectionOriginTime, currentTime),
        Math.max(this._selectionOriginTime, currentTime)));
  }

494 495
  _handleTimeSelectionMouseUp(event) {
    if (event.button !== 0) return;
496
    this._selectionOriginTime = -1;
497
    if (this._timeSelection.start === -1) return;
498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535
    const delta = this._timeSelection.end - this._timeSelection.start;
    if (delta <= 1 || isNaN(delta)) return;
    this._timeline.dispatchEvent(new SelectTimeEvent(
        this._timeSelection.start, this._timeSelection.end));
  }
}

class Legend {
  _timeline;
  _typesFilters = new Map();
  _typeClickHandler = this._handleTypeClick.bind(this);
  _filterPredicate = this.filter.bind(this);
  onFilter = () => {};

  constructor(table) {
    this._table = table;
  }

  set timeline(timeline) {
    this._timeline = timeline;
    const groups = timeline.getBreakdown();
    this._typesFilters = new Map(groups.map(each => [each.key, true]));
    this._colors =
        new Map(groups.map(each => [each.key, CSSColor.at(each.id)]));
  }

  get selection() {
    return this._timeline.selectionOrSelf;
  }

  get filterPredicate() {
    for (let visible of this._typesFilters.values()) {
      if (!visible) return this._filterPredicate;
    }
    return undefined;
  }

  colorForType(type) {
536 537 538 539 540 541
    let color = this._colors.get(type);
    if (color === undefined) {
      color = CSSColor.at(this._colors.size);
      this._colors.set(type, color);
    }
    return color;
542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595
  }

  filter(logEntry) {
    return this._typesFilters.get(logEntry.type);
  }

  update() {
    const tbody = DOM.tbody();
    const missingTypes = new Set(this._typesFilters.keys());
    this.selection.getBreakdown().forEach(group => {
      tbody.appendChild(this._addTypeRow(group));
      missingTypes.delete(group.key);
    });
    missingTypes.forEach(key => tbody.appendChild(this._row('', key, 0, '0%')));
    if (this._timeline.selection) {
      tbody.appendChild(
          this._row('', 'Selection', this.selection.length, '100%'));
    }
    tbody.appendChild(this._row('', 'All', this._timeline.length, ''));
    this._table.tBodies[0].replaceWith(tbody);
  }

  _row(color, type, count, percent) {
    const row = DOM.tr();
    row.appendChild(DOM.td(color));
    row.appendChild(DOM.td(type));
    row.appendChild(DOM.td(count.toString()));
    row.appendChild(DOM.td(percent));
    return row
  }

  _addTypeRow(group) {
    const color = this.colorForType(group.key);
    const colorDiv = DOM.div('colorbox');
    if (this._typesFilters.get(group.key)) {
      colorDiv.style.backgroundColor = color;
    } else {
      colorDiv.style.borderColor = color;
      colorDiv.style.backgroundColor = CSSColor.backgroundImage;
    }
    let percent = `${(group.count / this.selection.length * 100).toFixed(1)}%`;
    const row = this._row(colorDiv, group.key, group.count, percent);
    row.className = 'clickable';
    row.onclick = this._typeClickHandler;
    row.data = group.key;
    return row;
  }

  _handleTypeClick(e) {
    const type = e.currentTarget.data;
    this._typesFilters.set(type, !this._typesFilters.get(type));
    this.onFilter(type);
  }
}