helper.mjs 11.1 KB
Newer Older
1 2 3 4
// 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.

5
export class CSSColor {
6 7 8 9 10 11 12 13 14 15
  static _cache = new Map();

  static get(name) {
    let color = this._cache.get(name);
    if (color !== undefined) return color;
    const style = getComputedStyle(document.body);
    color = style.getPropertyValue(`--${name}`);
    if (color === undefined) {
      throw new Error(`CSS color does not exist: ${name}`);
    }
16 17
    color = color.trim();
    this._cache.set(name, color);
18 19
    return color;
  }
20

21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 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
  static reset() {
    this._cache.clear();
  }

  static get backgroundColor() {
    return this.get('background-color');
  }
  static get surfaceColor() {
    return this.get('surface-color');
  }
  static get primaryColor() {
    return this.get('primary-color');
  }
  static get secondaryColor() {
    return this.get('secondary-color');
  }
  static get onSurfaceColor() {
    return this.get('on-surface-color');
  }
  static get onBackgroundColor() {
    return this.get('on-background-color');
  }
  static get onPrimaryColor() {
    return this.get('on-primary-color');
  }
  static get onSecondaryColor() {
    return this.get('on-secondary-color');
  }
  static get defaultColor() {
    return this.get('default-color');
  }
  static get errorColor() {
    return this.get('error-color');
  }
  static get mapBackgroundColor() {
    return this.get('map-background-color');
  }
  static get timelineBackgroundColor() {
    return this.get('timeline-background-color');
  }
  static get red() {
    return this.get('red');
  }
  static get green() {
    return this.get('green');
  }
  static get yellow() {
    return this.get('yellow');
  }
  static get blue() {
    return this.get('blue');
  }
73

74 75 76
  static get orange() {
    return this.get('orange');
  }
77

78 79 80
  static get violet() {
    return this.get('violet');
  }
81

82 83 84
  static at(index) {
    return this.list[index % this.list.length];
  }
85

86
  static darken(hexColorString, amount = -50) {
87 88 89 90 91 92 93 94 95 96 97
    if (hexColorString[0] !== '#') {
      throw new Error(`Unsupported color: ${hexColorString}`);
    }
    let color = parseInt(hexColorString.substring(1), 16);
    let b = Math.min(Math.max((color & 0xFF) + amount, 0), 0xFF);
    let g = Math.min(Math.max(((color >> 8) & 0xFF) + amount, 0), 0xFF);
    let r = Math.min(Math.max(((color >> 16) & 0xFF) + amount, 0), 0xFF);
    color = (r << 16) + (g << 8) + b;
    return `#${color.toString(16).padStart(6, '0')}`;
  }

98 99 100 101 102 103 104 105 106 107 108 109
  static get list() {
    if (!this._colors) {
      this._colors = [
        this.green,
        this.violet,
        this.orange,
        this.yellow,
        this.primaryColor,
        this.red,
        this.blue,
        this.yellow,
        this.secondaryColor,
110 111 112 113 114 115 116 117 118
        this.darken(this.green),
        this.darken(this.violet),
        this.darken(this.orange),
        this.darken(this.yellow),
        this.darken(this.primaryColor),
        this.darken(this.red),
        this.darken(this.blue),
        this.darken(this.yellow),
        this.darken(this.secondaryColor),
119 120 121 122
      ];
    }
    return this._colors;
  }
123 124
}

125
export class DOM {
126 127
  static element(type, classes) {
    const node = document.createElement(type);
128 129 130 131 132 133 134 135 136 137 138 139
    if (classes !== undefined) {
      if (typeof classes === 'string') {
        node.className = classes;
      } else {
        DOM.addClasses(node, classes);
      }
    }
    return node;
  }

  static addClasses(node, classes) {
    const classList = node.classList;
140
    if (typeof classes === 'string') {
141
      classList.add(classes);
142
    } else {
143 144 145
      for (let i = 0; i < classes.length; i++) {
        classList.add(classes[i]);
      }
146 147 148
    }
    return node;
  }
149 150 151 152 153

  static text(string) {
    return document.createTextNode(string);
  }

154 155 156 157 158 159 160
  static button(label, clickHandler) {
    const button = DOM.element('button');
    button.innerText = label;
    button.onclick = clickHandler;
    return button;
  }

161 162 163 164
  static div(classes) {
    return this.element('div', classes);
  }

165
  static span(classes) {
166
    return this.element('span', classes);
167
  }
168 169 170 171 172 173 174

  static table(classes) {
    return this.element('table', classes);
  }

  static tbody(classes) {
    return this.element('tbody', classes);
175 176 177
  }

  static td(textOrNode, className) {
178
    const node = this.element('td');
179 180 181 182 183 184 185 186 187
    if (typeof textOrNode === 'object') {
      node.appendChild(textOrNode);
    } else if (textOrNode) {
      node.innerText = textOrNode;
    }
    if (className) node.className = className;
    return node;
  }

188 189
  static tr(classes) {
    return this.element('tr', classes);
190 191 192 193 194 195 196 197
  }

  static removeAllChildren(node) {
    let range = document.createRange();
    range.selectNodeContents(node);
    range.deleteContents();
  }

198 199 200 201 202 203 204 205 206 207 208
  static defineCustomElement(
      path, nameOrGenerator, maybeGenerator = undefined) {
    let generator = nameOrGenerator;
    let name = nameOrGenerator;
    if (typeof nameOrGenerator == 'function') {
      console.assert(maybeGenerator === undefined);
      name = path.substring(path.lastIndexOf('/') + 1, path.length);
    } else {
      console.assert(typeof nameOrGenerator == 'string');
      generator = maybeGenerator;
    }
209 210 211 212 213 214 215 216 217
    path = path + '-template.html';
    fetch(path)
        .then(stream => stream.text())
        .then(
            templateText =>
                customElements.define(name, generator(templateText)));
  }
}

218 219 220 221 222 223 224 225
const SVGNamespace = 'http://www.w3.org/2000/svg';
export class SVG {
  static element(type, classes) {
    const node = document.createElementNS(SVGNamespace, type);
    if (classes !== undefined) DOM.addClasses(node, classes);
    return node;
  }

226 227
  static svg(classes) {
    return this.element('svg', classes);
228 229 230 231 232 233
  }

  static rect(classes) {
    return this.element('rect', classes);
  }

234 235
  static g(classes) {
    return this.element('g', classes);
236 237 238
  }
}

239
export function $(id) {
240 241 242
  return document.querySelector(id)
}

243
export class V8CustomElement extends HTMLElement {
244
  _updateTimeoutId;
245
  _updateCallback = this.forceUpdate.bind(this);
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260

  constructor(templateText) {
    super();
    const shadowRoot = this.attachShadow({mode: 'open'});
    shadowRoot.innerHTML = templateText;
  }

  $(id) {
    return this.shadowRoot.querySelector(id);
  }

  querySelectorAll(query) {
    return this.shadowRoot.querySelectorAll(query);
  }

261
  requestUpdate(useAnimation = false) {
262 263 264 265 266 267 268 269 270 271
    if (useAnimation) {
      window.cancelAnimationFrame(this._updateTimeoutId);
      this._updateTimeoutId =
          window.requestAnimationFrame(this._updateCallback);
    } else {
      // Use timeout tasks to asynchronously update the UI without blocking.
      clearTimeout(this._updateTimeoutId);
      const kDelayMs = 5;
      this._updateTimeoutId = setTimeout(this._updateCallback, kDelayMs);
    }
272 273
  }

274 275 276 277
  forceUpdate() {
    this._update();
  }

278 279 280 281 282
  _update() {
    throw Error('Subclass responsibility');
  }
}

283 284 285 286
export class CollapsableElement extends V8CustomElement {
  constructor(templateText) {
    super(templateText);
    this._hasPendingUpdate = false;
287
    this._closer.onclick = _ => this._requestUpdateIfVisible();
288 289
  }

290 291 292 293
  get _closer() {
    return this.$('#closer');
  }

294
  get _contentIsVisible() {
295 296 297
    return !this._closer.checked;
  }

298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
  hide() {
    if (this._contentIsVisible) {
      this._closer.checked = true;
      this._requestUpdateIfVisible();
    }
    this.scrollIntoView();
  }

  show() {
    if (!this._contentIsVisible) {
      this._closer.checked = false;
      this._requestUpdateIfVisible();
    }
    this.scrollIntoView();
  }

314 315 316 317
  requestUpdate(useAnimation = false) {
    // A pending update will be resolved later, no need to try again.
    if (this._hasPendingUpdate) return;
    this._hasPendingUpdate = true;
318
    this._requestUpdateIfVisible(useAnimation);
319 320
  }

321
  _requestUpdateIfVisible(useAnimation = true) {
322
    if (!this._contentIsVisible) return;
323 324 325 326 327 328 329 330 331
    return super.requestUpdate(useAnimation);
  }

  forceUpdate() {
    this._hasPendingUpdate = false;
    super.forceUpdate();
  }
}

332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
export class ExpandableText {
  constructor(node, string, limit = 200) {
    this._node = node;
    this._string = string;
    this._delta = limit / 2;
    this._start = 0;
    this._end = string.length;
    this._button = this._createExpandButton();
    this.expand();
  }

  _createExpandButton() {
    const button = DOM.element('button');
    button.innerText = '...';
    button.onclick = (e) => {
      e.stopImmediatePropagation();
      this.expand()
    };
    return button;
  }

  expand() {
    DOM.removeAllChildren(this._node);
    this._start = this._start + this._delta;
    this._end = this._end - this._delta;
    if (this._start >= this._end) {
      this._node.innerText = this._string;
      this._button.onclick = undefined;
      return;
    }
    this._node.appendChild(DOM.text(this._string.substring(0, this._start)));
    this._node.appendChild(this._button);
    this._node.appendChild(
        DOM.text(this._string.substring(this._end, this._string.length)));
  }
}

369
export class Chunked {
370 371 372 373 374
  constructor(iterable, limit) {
    this._iterator = iterable[Symbol.iterator]();
    this._limit = limit;
  }

375 376
  * next(limit = undefined) {
    for (let i = 0; i < (limit ?? this._limit); i++) {
377 378 379 380 381 382 383 384 385 386 387 388 389 390
      const {value, done} = this._iterator.next();
      if (done) {
        this._iterator = undefined;
        return;
      };
      yield value;
    }
  }

  get hasMore() {
    return this._iterator !== undefined;
  }
}

391
export class LazyTable {
392
  constructor(table, rowData, rowElementCreator, limit = 100) {
393
    this._table = table;
394
    this._chunkedRowData = new Chunked(rowData, limit);
395
    this._rowElementCreator = rowElementCreator;
396 397 398 399 400
    if (table.tBodies.length == 0) {
      table.appendChild(DOM.tbody());
    } else {
      table.replaceChild(DOM.tbody(), table.tBodies[0]);
    }
401
    if (!table.tFoot) this._addFooter();
402
    table.tFoot.addEventListener('click', this._clickHandler);
403 404 405
    this._addMoreRows();
  }

406 407 408 409 410 411 412 413 414 415 416 417 418 419
  _addFooter() {
    const td = DOM.td();
    td.setAttribute('colspan', 100);
    for (let addCount of [10, 100, 250, 500]) {
      const button = DOM.element('button');
      button.innerText = `+${addCount}`;
      button.onclick = (e) => this._addMoreRows(addCount);
      td.appendChild(button);
    }
    this._table.appendChild(DOM.element('tfoot'))
        .appendChild(DOM.tr())
        .appendChild(td);
  }

420
  _addMoreRows(count = undefined) {
421
    const fragment = new DocumentFragment();
422
    for (let row of this._chunkedRowData.next(count)) {
423 424 425
      const tr = this._rowElementCreator(row);
      fragment.appendChild(tr);
    }
426 427
    this._table.tBodies[0].appendChild(fragment);
    if (!this._chunkedRowData.hasMore) {
428
      DOM.removeAllChildren(this._table.tFoot);
429
    }
430 431 432
  }
}

433 434 435 436 437 438 439 440 441 442
export function gradientStopsFromGroups(
    totalLength, maxHeight, groups, colorFn) {
  const kMaxHeight = maxHeight === '%' ? 100 : maxHeight;
  const kUnit = maxHeight === '%' ? '%' : 'px';
  let increment = 0;
  let lastHeight = 0.0;
  const stops = [];
  for (let group of groups) {
    const color = colorFn(group.key);
    increment += group.count;
443
    const height = (increment / totalLength * kMaxHeight) | 0;
444 445 446 447 448 449
    stops.push(`${color} ${lastHeight}${kUnit} ${height}${kUnit}`)
    lastHeight = height;
  }
  return stops;
}

450
export * from '../helper.mjs';