blob: 11b6fd852dd7cbe0cb049ead4f75bf8a5593137c [file] [log] [blame]
Blink Reformat4c46d092018-04-07 15:32:371/*
2 * Copyright (C) 2013 Google Inc. All rights reserved.
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions are
6 * met:
7 *
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above
11 * copyright notice, this list of conditions and the following disclaimer
12 * in the documentation and/or other materials provided with the
13 * distribution.
14 * * Neither the name of Google Inc. nor the names of its
15 * contributors may be used to endorse or promote products derived from
16 * this software without specific prior written permission.
17 *
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 */
30
31/**
32 * @unrestricted
33 */
34Console.ConsoleViewport = class {
35 /**
36 * @param {!Console.ConsoleViewportProvider} provider
37 */
38 constructor(provider) {
39 this.element = createElement('div');
40 this.element.style.overflow = 'auto';
41 this._topGapElement = this.element.createChild('div');
42 this._topGapElement.style.height = '0px';
43 this._topGapElement.style.color = 'transparent';
44 this._contentElement = this.element.createChild('div');
45 this._bottomGapElement = this.element.createChild('div');
46 this._bottomGapElement.style.height = '0px';
47 this._bottomGapElement.style.color = 'transparent';
48
49 // Text content needed for range intersection checks in _updateSelectionModel.
50 // Use Unicode ZERO WIDTH NO-BREAK SPACE, which avoids contributing any height to the element's layout overflow.
51 this._topGapElement.textContent = '\uFEFF';
52 this._bottomGapElement.textContent = '\uFEFF';
53
Joel Einbinderca8fa5a2018-08-24 23:30:2554 UI.ARIAUtils.markAsHidden(this._topGapElement);
55 UI.ARIAUtils.markAsHidden(this._bottomGapElement);
56
Blink Reformat4c46d092018-04-07 15:32:3757 this._provider = provider;
58 this.element.addEventListener('scroll', this._onScroll.bind(this), false);
59 this.element.addEventListener('copy', this._onCopy.bind(this), false);
60 this.element.addEventListener('dragstart', this._onDragStart.bind(this), false);
Erik Luo39452ff2018-09-01 01:08:0761 this._keyboardNavigationEnabled = Runtime.experiments.isEnabled('consoleKeyboardNavigation');
62 if (this._keyboardNavigationEnabled) {
Erik Luob5bfff42018-09-20 02:52:3963 this._contentElement.addEventListener('focusin', this._onFocusIn.bind(this), false);
64 this._contentElement.addEventListener('focusout', this._onFocusOut.bind(this), false);
65 this._contentElement.addEventListener('keydown', this._onKeyDown.bind(this), false);
Erik Luo39452ff2018-09-01 01:08:0766 }
67 this._virtualSelectedIndex = -1;
Erik Luob5bfff42018-09-20 02:52:3968 this._contentElement.tabIndex = -1;
Blink Reformat4c46d092018-04-07 15:32:3769
70 this._firstActiveIndex = -1;
71 this._lastActiveIndex = -1;
72 this._renderedItems = [];
73 this._anchorSelection = null;
74 this._headSelection = null;
75 this._itemCount = 0;
76 this._cumulativeHeights = new Int32Array(0);
77 this._muteCopyHandler = false;
78
79 // Listen for any changes to descendants and trigger a refresh. This ensures
80 // that items updated asynchronously will not break stick-to-bottom behavior
81 // if they change the scroll height.
82 this._observer = new MutationObserver(this.refresh.bind(this));
83 this._observerConfig = {childList: true, subtree: true};
84 }
85
86 /**
87 * @return {boolean}
88 */
89 stickToBottom() {
90 return this._stickToBottom;
91 }
92
93 /**
94 * @param {boolean} value
95 */
96 setStickToBottom(value) {
97 this._stickToBottom = value;
98 if (this._stickToBottom)
99 this._observer.observe(this._contentElement, this._observerConfig);
100 else
101 this._observer.disconnect();
102 }
103
Erik Luoad6c91c2018-12-06 03:28:42104 /**
105 * @return {boolean}
106 */
107 hasVirtualSelection() {
108 return this._virtualSelectedIndex !== -1;
109 }
110
Blink Reformat4c46d092018-04-07 15:32:37111 copyWithStyles() {
112 this._muteCopyHandler = true;
113 this.element.ownerDocument.execCommand('copy');
114 this._muteCopyHandler = false;
115 }
116
117 /**
118 * @param {!Event} event
119 */
120 _onCopy(event) {
121 if (this._muteCopyHandler)
122 return;
123 const text = this._selectedText();
124 if (!text)
125 return;
126 event.preventDefault();
127 event.clipboardData.setData('text/plain', text);
128 }
129
130 /**
131 * @param {!Event} event
132 */
Erik Luo39452ff2018-09-01 01:08:07133 _onFocusIn(event) {
Erik Luob5bfff42018-09-20 02:52:39134 const renderedIndex = this._renderedItems.findIndex(item => item.element().isSelfOrAncestor(event.target));
135 if (renderedIndex !== -1)
136 this._virtualSelectedIndex = this._firstActiveIndex + renderedIndex;
Erik Luofc6a6302018-11-02 06:48:52137 let focusLastChild = false;
Erik Luo39452ff2018-09-01 01:08:07138 // Make default selection when moving from external (e.g. prompt) to the container.
139 if (this._virtualSelectedIndex === -1 && this._isOutsideViewport(/** @type {?Element} */ (event.relatedTarget)) &&
Erik Luoad6c91c2018-12-06 03:28:42140 event.target === this._contentElement && this._itemCount) {
Erik Luofc6a6302018-11-02 06:48:52141 focusLastChild = true;
Erik Luo39452ff2018-09-01 01:08:07142 this._virtualSelectedIndex = this._itemCount - 1;
Erik Luo840be6b2018-12-03 20:54:27143
144 // Update stick to bottom before scrolling into view.
145 this.refresh();
146 this.scrollItemIntoView(this._virtualSelectedIndex);
Erik Luofc6a6302018-11-02 06:48:52147 }
148 this._updateFocusedItem(focusLastChild);
Erik Luo39452ff2018-09-01 01:08:07149 }
150
151 /**
152 * @param {!Event} event
153 */
154 _onFocusOut(event) {
155 // Remove selection when focus moves to external location (e.g. prompt).
156 if (this._isOutsideViewport(/** @type {?Element} */ (event.relatedTarget)))
157 this._virtualSelectedIndex = -1;
158 this._updateFocusedItem();
159 }
160
161 /**
162 * @param {?Element} element
163 * @return {boolean}
164 */
165 _isOutsideViewport(element) {
Erik Luob5bfff42018-09-20 02:52:39166 return !!element && !element.isSelfOrDescendant(this._contentElement);
Erik Luo39452ff2018-09-01 01:08:07167 }
168
169 /**
170 * @param {!Event} event
171 */
Blink Reformat4c46d092018-04-07 15:32:37172 _onDragStart(event) {
173 const text = this._selectedText();
174 if (!text)
175 return false;
176 event.dataTransfer.clearData();
177 event.dataTransfer.setData('text/plain', text);
178 event.dataTransfer.effectAllowed = 'copy';
179 return true;
180 }
181
182 /**
Erik Luo39452ff2018-09-01 01:08:07183 * @param {!Event} event
184 */
185 _onKeyDown(event) {
Erik Luob5bfff42018-09-20 02:52:39186 if (UI.isEditing() || !this._itemCount || event.shiftKey)
Erik Luo39452ff2018-09-01 01:08:07187 return;
Erik Luo0b8282e2018-10-08 20:37:46188 let isArrowUp = false;
Erik Luo39452ff2018-09-01 01:08:07189 switch (event.key) {
190 case 'ArrowUp':
Erik Luo0b8282e2018-10-08 20:37:46191 if (this._virtualSelectedIndex > 0) {
192 isArrowUp = true;
193 this._virtualSelectedIndex--;
194 } else {
195 return;
196 }
Erik Luo39452ff2018-09-01 01:08:07197 break;
198 case 'ArrowDown':
Erik Luo0b8282e2018-10-08 20:37:46199 if (this._virtualSelectedIndex < this._itemCount - 1)
200 this._virtualSelectedIndex++;
201 else
202 return;
Erik Luo39452ff2018-09-01 01:08:07203 break;
204 case 'Home':
205 this._virtualSelectedIndex = 0;
206 break;
207 case 'End':
208 this._virtualSelectedIndex = this._itemCount - 1;
209 break;
210 default:
211 return;
212 }
213 event.consume(true);
214 this.scrollItemIntoView(this._virtualSelectedIndex);
Erik Luo0b8282e2018-10-08 20:37:46215 this._updateFocusedItem(isArrowUp);
Erik Luo39452ff2018-09-01 01:08:07216 }
217
Erik Luo0b8282e2018-10-08 20:37:46218 /**
219 * @param {boolean=} focusLastChild
220 */
221 _updateFocusedItem(focusLastChild) {
Erik Luo39452ff2018-09-01 01:08:07222 const selectedElement = this.renderedElementAt(this._virtualSelectedIndex);
223 const changed = this._lastSelectedElement !== selectedElement;
Erik Luob5bfff42018-09-20 02:52:39224 const containerHasFocus = this._contentElement === this.element.ownerDocument.deepActiveElement();
Erik Luo39452ff2018-09-01 01:08:07225 if (this._lastSelectedElement && changed)
226 this._lastSelectedElement.classList.remove('console-selected');
Erik Luo840be6b2018-12-03 20:54:27227 if (selectedElement && (focusLastChild || changed || containerHasFocus) && this.element.hasFocus()) {
Erik Luo39452ff2018-09-01 01:08:07228 selectedElement.classList.add('console-selected');
Erik Luob5bfff42018-09-20 02:52:39229 // Do not focus the message if something within holds focus (e.g. object).
Erik Luo840be6b2018-12-03 20:54:27230 if (focusLastChild) {
231 this.setStickToBottom(false);
232 this._renderedItems[this._virtualSelectedIndex - this._firstActiveIndex].focusLastChildOrSelf();
233 } else if (!selectedElement.hasFocus()) {
234 focusWithoutScroll(selectedElement);
Erik Luo0b8282e2018-10-08 20:37:46235 }
Erik Luo39452ff2018-09-01 01:08:07236 }
237 if (this._itemCount && !this._contentElement.hasFocus())
Erik Luob5bfff42018-09-20 02:52:39238 this._contentElement.tabIndex = 0;
Erik Luo39452ff2018-09-01 01:08:07239 else
Erik Luob5bfff42018-09-20 02:52:39240 this._contentElement.tabIndex = -1;
Erik Luo39452ff2018-09-01 01:08:07241 this._lastSelectedElement = selectedElement;
242
243 /**
244 * @suppress {checkTypes}
245 * @param {!Element} element
246 */
247 function focusWithoutScroll(element) {
248 // TODO(luoe): Closure has an outdated typedef for Element.prototype.focus.
249 element.focus({preventScroll: true});
250 }
251 }
252
253 /**
Blink Reformat4c46d092018-04-07 15:32:37254 * @return {!Element}
255 */
256 contentElement() {
257 return this._contentElement;
258 }
259
260 invalidate() {
261 delete this._cachedProviderElements;
262 this._itemCount = this._provider.itemCount();
Erik Luo39452ff2018-09-01 01:08:07263 if (this._virtualSelectedIndex > this._itemCount - 1)
264 this._virtualSelectedIndex = this._itemCount - 1;
Blink Reformat4c46d092018-04-07 15:32:37265 this._rebuildCumulativeHeights();
266 this.refresh();
267 }
268
269 /**
270 * @param {number} index
271 * @return {?Console.ConsoleViewportElement}
272 */
273 _providerElement(index) {
274 if (!this._cachedProviderElements)
275 this._cachedProviderElements = new Array(this._itemCount);
276 let element = this._cachedProviderElements[index];
277 if (!element) {
278 element = this._provider.itemElement(index);
279 this._cachedProviderElements[index] = element;
280 }
281 return element;
282 }
283
284 _rebuildCumulativeHeights() {
285 const firstActiveIndex = this._firstActiveIndex;
286 const lastActiveIndex = this._lastActiveIndex;
287 let height = 0;
288 this._cumulativeHeights = new Int32Array(this._itemCount);
289 for (let i = 0; i < this._itemCount; ++i) {
290 if (firstActiveIndex <= i && i - firstActiveIndex < this._renderedItems.length && i <= lastActiveIndex)
291 height += this._renderedItems[i - firstActiveIndex].element().offsetHeight;
292 else
293 height += this._provider.fastHeight(i);
294 this._cumulativeHeights[i] = height;
295 }
296 }
297
298 _rebuildCumulativeHeightsIfNeeded() {
Erik Luo4b002322018-07-30 21:23:31299 let totalCachedHeight = 0;
300 let totalMeasuredHeight = 0;
Blink Reformat4c46d092018-04-07 15:32:37301 // Check whether current items in DOM have changed heights. Tolerate 1-pixel
302 // error due to double-to-integer rounding errors.
303 for (let i = 0; i < this._renderedItems.length; ++i) {
304 const cachedItemHeight = this._cachedItemHeight(this._firstActiveIndex + i);
Erik Luo4b002322018-07-30 21:23:31305 const measuredHeight = this._renderedItems[i].element().offsetHeight;
306 if (Math.abs(cachedItemHeight - measuredHeight) > 1) {
Blink Reformat4c46d092018-04-07 15:32:37307 this._rebuildCumulativeHeights();
Erik Luo4b002322018-07-30 21:23:31308 return;
309 }
310 totalMeasuredHeight += measuredHeight;
311 totalCachedHeight += cachedItemHeight;
312 if (Math.abs(totalCachedHeight - totalMeasuredHeight) > 1) {
313 this._rebuildCumulativeHeights();
314 return;
Blink Reformat4c46d092018-04-07 15:32:37315 }
316 }
317 }
318
319 /**
320 * @param {number} index
321 * @return {number}
322 */
323 _cachedItemHeight(index) {
324 return index === 0 ? this._cumulativeHeights[0] :
325 this._cumulativeHeights[index] - this._cumulativeHeights[index - 1];
326 }
327
328 /**
329 * @param {?Selection} selection
330 * @suppressGlobalPropertiesCheck
331 */
332 _isSelectionBackwards(selection) {
333 if (!selection || !selection.rangeCount)
334 return false;
335 const range = document.createRange();
336 range.setStart(selection.anchorNode, selection.anchorOffset);
337 range.setEnd(selection.focusNode, selection.focusOffset);
338 return range.collapsed;
339 }
340
341 /**
342 * @param {number} itemIndex
343 * @param {!Node} node
344 * @param {number} offset
345 * @return {!{item: number, node: !Node, offset: number}}
346 */
347 _createSelectionModel(itemIndex, node, offset) {
348 return {item: itemIndex, node: node, offset: offset};
349 }
350
351 /**
352 * @param {?Selection} selection
353 */
354 _updateSelectionModel(selection) {
355 const range = selection && selection.rangeCount ? selection.getRangeAt(0) : null;
356 if (!range || selection.isCollapsed || !this.element.hasSelection()) {
357 this._headSelection = null;
358 this._anchorSelection = null;
359 return false;
360 }
361
362 let firstSelected = Number.MAX_VALUE;
363 let lastSelected = -1;
364
365 let hasVisibleSelection = false;
366 for (let i = 0; i < this._renderedItems.length; ++i) {
367 if (range.intersectsNode(this._renderedItems[i].element())) {
368 const index = i + this._firstActiveIndex;
369 firstSelected = Math.min(firstSelected, index);
370 lastSelected = Math.max(lastSelected, index);
371 hasVisibleSelection = true;
372 }
373 }
374 if (hasVisibleSelection) {
375 firstSelected =
376 this._createSelectionModel(firstSelected, /** @type {!Node} */ (range.startContainer), range.startOffset);
377 lastSelected =
378 this._createSelectionModel(lastSelected, /** @type {!Node} */ (range.endContainer), range.endOffset);
379 }
380 const topOverlap = range.intersectsNode(this._topGapElement) && this._topGapElement._active;
381 const bottomOverlap = range.intersectsNode(this._bottomGapElement) && this._bottomGapElement._active;
382 if (!topOverlap && !bottomOverlap && !hasVisibleSelection) {
383 this._headSelection = null;
384 this._anchorSelection = null;
385 return false;
386 }
387
388 if (!this._anchorSelection || !this._headSelection) {
389 this._anchorSelection = this._createSelectionModel(0, this.element, 0);
390 this._headSelection = this._createSelectionModel(this._itemCount - 1, this.element, this.element.children.length);
391 this._selectionIsBackward = false;
392 }
393
394 const isBackward = this._isSelectionBackwards(selection);
395 const startSelection = this._selectionIsBackward ? this._headSelection : this._anchorSelection;
396 const endSelection = this._selectionIsBackward ? this._anchorSelection : this._headSelection;
397 if (topOverlap && bottomOverlap && hasVisibleSelection) {
398 firstSelected = firstSelected.item < startSelection.item ? firstSelected : startSelection;
399 lastSelected = lastSelected.item > endSelection.item ? lastSelected : endSelection;
400 } else if (!hasVisibleSelection) {
401 firstSelected = startSelection;
402 lastSelected = endSelection;
403 } else if (topOverlap) {
404 firstSelected = isBackward ? this._headSelection : this._anchorSelection;
405 } else if (bottomOverlap) {
406 lastSelected = isBackward ? this._anchorSelection : this._headSelection;
407 }
408
409 if (isBackward) {
410 this._anchorSelection = lastSelected;
411 this._headSelection = firstSelected;
412 } else {
413 this._anchorSelection = firstSelected;
414 this._headSelection = lastSelected;
415 }
416 this._selectionIsBackward = isBackward;
417 return true;
418 }
419
420 /**
421 * @param {?Selection} selection
422 */
423 _restoreSelection(selection) {
424 let anchorElement = null;
425 let anchorOffset;
426 if (this._firstActiveIndex <= this._anchorSelection.item && this._anchorSelection.item <= this._lastActiveIndex) {
427 anchorElement = this._anchorSelection.node;
428 anchorOffset = this._anchorSelection.offset;
429 } else {
430 if (this._anchorSelection.item < this._firstActiveIndex)
431 anchorElement = this._topGapElement;
432 else if (this._anchorSelection.item > this._lastActiveIndex)
433 anchorElement = this._bottomGapElement;
434 anchorOffset = this._selectionIsBackward ? 1 : 0;
435 }
436
437 let headElement = null;
438 let headOffset;
439 if (this._firstActiveIndex <= this._headSelection.item && this._headSelection.item <= this._lastActiveIndex) {
440 headElement = this._headSelection.node;
441 headOffset = this._headSelection.offset;
442 } else {
443 if (this._headSelection.item < this._firstActiveIndex)
444 headElement = this._topGapElement;
445 else if (this._headSelection.item > this._lastActiveIndex)
446 headElement = this._bottomGapElement;
447 headOffset = this._selectionIsBackward ? 0 : 1;
448 }
449
450 selection.setBaseAndExtent(anchorElement, anchorOffset, headElement, headOffset);
451 }
452
453 refresh() {
454 this._observer.disconnect();
455 this._innerRefresh();
456 if (this._stickToBottom)
457 this._observer.observe(this._contentElement, this._observerConfig);
458 }
459
460 _innerRefresh() {
461 if (!this._visibleHeight())
462 return; // Do nothing for invisible controls.
463
464 if (!this._itemCount) {
465 for (let i = 0; i < this._renderedItems.length; ++i)
466 this._renderedItems[i].willHide();
467 this._renderedItems = [];
468 this._contentElement.removeChildren();
469 this._topGapElement.style.height = '0px';
470 this._bottomGapElement.style.height = '0px';
471 this._firstActiveIndex = -1;
472 this._lastActiveIndex = -1;
Erik Luo39452ff2018-09-01 01:08:07473 if (this._keyboardNavigationEnabled)
474 this._updateFocusedItem();
Blink Reformat4c46d092018-04-07 15:32:37475 return;
476 }
477
478 const selection = this.element.getComponentSelection();
479 const shouldRestoreSelection = this._updateSelectionModel(selection);
480
481 const visibleFrom = this.element.scrollTop;
482 const visibleHeight = this._visibleHeight();
483 const activeHeight = visibleHeight * 2;
484 this._rebuildCumulativeHeightsIfNeeded();
485
486 // When the viewport is scrolled to the bottom, using the cumulative heights estimate is not
487 // precise enough to determine next visible indices. This stickToBottom check avoids extra
488 // calls to refresh in those cases.
489 if (this._stickToBottom) {
490 this._firstActiveIndex =
491 Math.max(this._itemCount - Math.ceil(activeHeight / this._provider.minimumRowHeight()), 0);
492 this._lastActiveIndex = this._itemCount - 1;
493 } else {
494 this._firstActiveIndex =
495 Math.max(this._cumulativeHeights.lowerBound(visibleFrom + 1 - (activeHeight - visibleHeight) / 2), 0);
496 // Proactively render more rows in case some of them will be collapsed without triggering refresh. @see crbug.com/390169
497 this._lastActiveIndex = this._firstActiveIndex + Math.ceil(activeHeight / this._provider.minimumRowHeight()) - 1;
498 this._lastActiveIndex = Math.min(this._lastActiveIndex, this._itemCount - 1);
499 }
500
501 const topGapHeight = this._cumulativeHeights[this._firstActiveIndex - 1] || 0;
502 const bottomGapHeight =
503 this._cumulativeHeights[this._cumulativeHeights.length - 1] - this._cumulativeHeights[this._lastActiveIndex];
504
505 /**
506 * @this {Console.ConsoleViewport}
507 */
508 function prepare() {
509 this._topGapElement.style.height = topGapHeight + 'px';
510 this._bottomGapElement.style.height = bottomGapHeight + 'px';
511 this._topGapElement._active = !!topGapHeight;
512 this._bottomGapElement._active = !!bottomGapHeight;
513 this._contentElement.style.setProperty('height', '10000000px');
514 }
515
516 this._partialViewportUpdate(prepare.bind(this));
517 this._contentElement.style.removeProperty('height');
518 // Should be the last call in the method as it might force layout.
519 if (shouldRestoreSelection)
520 this._restoreSelection(selection);
521 if (this._stickToBottom)
522 this.element.scrollTop = 10000000;
523 }
524
525 /**
526 * @param {function()} prepare
527 */
528 _partialViewportUpdate(prepare) {
529 const itemsToRender = new Set();
530 for (let i = this._firstActiveIndex; i <= this._lastActiveIndex; ++i)
531 itemsToRender.add(this._providerElement(i));
532 const willBeHidden = this._renderedItems.filter(item => !itemsToRender.has(item));
533 for (let i = 0; i < willBeHidden.length; ++i)
534 willBeHidden[i].willHide();
535 prepare();
Erik Luo39452ff2018-09-01 01:08:07536 let hadFocus = false;
537 for (let i = 0; i < willBeHidden.length; ++i) {
538 if (this._keyboardNavigationEnabled)
539 hadFocus = hadFocus || willBeHidden[i].element().hasFocus();
Blink Reformat4c46d092018-04-07 15:32:37540 willBeHidden[i].element().remove();
Erik Luo39452ff2018-09-01 01:08:07541 }
Blink Reformat4c46d092018-04-07 15:32:37542
543 const wasShown = [];
544 let anchor = this._contentElement.firstChild;
545 for (const viewportElement of itemsToRender) {
546 const element = viewportElement.element();
547 if (element !== anchor) {
548 const shouldCallWasShown = !element.parentElement;
549 if (shouldCallWasShown)
550 wasShown.push(viewportElement);
551 this._contentElement.insertBefore(element, anchor);
552 } else {
553 anchor = anchor.nextSibling;
554 }
555 }
556 for (let i = 0; i < wasShown.length; ++i)
557 wasShown[i].wasShown();
558 this._renderedItems = Array.from(itemsToRender);
Erik Luo39452ff2018-09-01 01:08:07559
560 if (this._keyboardNavigationEnabled) {
561 if (hadFocus)
Erik Luob5bfff42018-09-20 02:52:39562 this._contentElement.focus();
Erik Luo39452ff2018-09-01 01:08:07563 this._updateFocusedItem();
564 }
Blink Reformat4c46d092018-04-07 15:32:37565 }
566
567 /**
568 * @return {?string}
569 */
570 _selectedText() {
571 this._updateSelectionModel(this.element.getComponentSelection());
572 if (!this._headSelection || !this._anchorSelection)
573 return null;
574
575 let startSelection = null;
576 let endSelection = null;
577 if (this._selectionIsBackward) {
578 startSelection = this._headSelection;
579 endSelection = this._anchorSelection;
580 } else {
581 startSelection = this._anchorSelection;
582 endSelection = this._headSelection;
583 }
584
585 const textLines = [];
586 for (let i = startSelection.item; i <= endSelection.item; ++i) {
587 const element = this._providerElement(i).element();
588 const lineContent = element.childTextNodes().map(Components.Linkifier.untruncatedNodeText).join('');
589 textLines.push(lineContent);
590 }
591
592 const endSelectionElement = this._providerElement(endSelection.item).element();
593 if (endSelection.node && endSelection.node.isSelfOrDescendant(endSelectionElement)) {
594 const itemTextOffset = this._textOffsetInNode(endSelectionElement, endSelection.node, endSelection.offset);
595 textLines[textLines.length - 1] = textLines.peekLast().substring(0, itemTextOffset);
596 }
597
598 const startSelectionElement = this._providerElement(startSelection.item).element();
599 if (startSelection.node && startSelection.node.isSelfOrDescendant(startSelectionElement)) {
600 const itemTextOffset = this._textOffsetInNode(startSelectionElement, startSelection.node, startSelection.offset);
601 textLines[0] = textLines[0].substring(itemTextOffset);
602 }
603
604 return textLines.join('\n');
605 }
606
607 /**
608 * @param {!Element} itemElement
609 * @param {!Node} selectionNode
610 * @param {number} offset
611 * @return {number}
612 */
613 _textOffsetInNode(itemElement, selectionNode, offset) {
614 // If the selectionNode is not a TextNode, we may need to convert a child offset into a character offset.
615 if (selectionNode.nodeType !== Node.TEXT_NODE) {
616 if (offset < selectionNode.childNodes.length) {
617 selectionNode = /** @type {!Node} */ (selectionNode.childNodes.item(offset));
618 offset = 0;
619 } else {
620 offset = selectionNode.textContent.length;
621 }
622 }
623
624 let chars = 0;
625 let node = itemElement;
626 while ((node = node.traverseNextNode(itemElement)) && node !== selectionNode) {
627 if (node.nodeType !== Node.TEXT_NODE || node.parentElement.nodeName === 'STYLE' ||
628 node.parentElement.nodeName === 'SCRIPT')
629 continue;
630 chars += Components.Linkifier.untruncatedNodeText(node).length;
631 }
632 // If the selected node text was truncated, treat any non-zero offset as the full length.
633 const untruncatedContainerLength = Components.Linkifier.untruncatedNodeText(selectionNode).length;
634 if (offset > 0 && untruncatedContainerLength !== selectionNode.textContent.length)
635 offset = untruncatedContainerLength;
636 return chars + offset;
637 }
638
639 /**
640 * @param {!Event} event
641 */
642 _onScroll(event) {
643 this.refresh();
644 }
645
646 /**
647 * @return {number}
648 */
649 firstVisibleIndex() {
650 if (!this._cumulativeHeights.length)
651 return -1;
652 this._rebuildCumulativeHeightsIfNeeded();
653 return this._cumulativeHeights.lowerBound(this.element.scrollTop + 1);
654 }
655
656 /**
657 * @return {number}
658 */
659 lastVisibleIndex() {
660 if (!this._cumulativeHeights.length)
661 return -1;
662 this._rebuildCumulativeHeightsIfNeeded();
663 const scrollBottom = this.element.scrollTop + this.element.clientHeight;
664 const right = this._itemCount - 1;
665 return this._cumulativeHeights.lowerBound(scrollBottom, undefined, undefined, right);
666 }
667
668 /**
669 * @return {?Element}
670 */
671 renderedElementAt(index) {
Erik Luo39452ff2018-09-01 01:08:07672 if (index === -1 || index < this._firstActiveIndex || index > this._lastActiveIndex)
Blink Reformat4c46d092018-04-07 15:32:37673 return null;
674 return this._renderedItems[index - this._firstActiveIndex].element();
675 }
676
677 /**
678 * @param {number} index
679 * @param {boolean=} makeLast
680 */
681 scrollItemIntoView(index, makeLast) {
682 const firstVisibleIndex = this.firstVisibleIndex();
683 const lastVisibleIndex = this.lastVisibleIndex();
684 if (index > firstVisibleIndex && index < lastVisibleIndex)
685 return;
Erik Luo4b002322018-07-30 21:23:31686 // If the prompt is visible, then the last item must be fully on screen.
687 if (index === lastVisibleIndex && this._cumulativeHeights[index] <= this.element.scrollTop + this._visibleHeight())
688 return;
Blink Reformat4c46d092018-04-07 15:32:37689 if (makeLast)
690 this.forceScrollItemToBeLast(index);
691 else if (index <= firstVisibleIndex)
692 this.forceScrollItemToBeFirst(index);
693 else if (index >= lastVisibleIndex)
694 this.forceScrollItemToBeLast(index);
695 }
696
697 /**
698 * @param {number} index
699 */
700 forceScrollItemToBeFirst(index) {
701 console.assert(index >= 0 && index < this._itemCount, 'Cannot scroll item at invalid index');
702 this.setStickToBottom(false);
703 this._rebuildCumulativeHeightsIfNeeded();
704 this.element.scrollTop = index > 0 ? this._cumulativeHeights[index - 1] : 0;
705 if (this.element.isScrolledToBottom())
706 this.setStickToBottom(true);
707 this.refresh();
Erik Luo4b002322018-07-30 21:23:31708 // After refresh, the item is in DOM, but may not be visible (items above were larger than expected).
709 this.renderedElementAt(index).scrollIntoView(true /* alignTop */);
Blink Reformat4c46d092018-04-07 15:32:37710 }
711
712 /**
713 * @param {number} index
714 */
715 forceScrollItemToBeLast(index) {
716 console.assert(index >= 0 && index < this._itemCount, 'Cannot scroll item at invalid index');
717 this.setStickToBottom(false);
718 this._rebuildCumulativeHeightsIfNeeded();
719 this.element.scrollTop = this._cumulativeHeights[index] - this._visibleHeight();
720 if (this.element.isScrolledToBottom())
721 this.setStickToBottom(true);
722 this.refresh();
Erik Luo4b002322018-07-30 21:23:31723 // After refresh, the item is in DOM, but may not be visible (items above were larger than expected).
724 this.renderedElementAt(index).scrollIntoView(false /* alignTop */);
Blink Reformat4c46d092018-04-07 15:32:37725 }
726
727 /**
728 * @return {number}
729 */
730 _visibleHeight() {
731 // Use offsetHeight instead of clientHeight to avoid being affected by horizontal scroll.
732 return this.element.offsetHeight;
733 }
734};
735
736/**
737 * @interface
738 */
739Console.ConsoleViewportProvider = function() {};
740
741Console.ConsoleViewportProvider.prototype = {
742 /**
743 * @param {number} index
744 * @return {number}
745 */
746 fastHeight(index) {
747 return 0;
748 },
749
750 /**
751 * @return {number}
752 */
753 itemCount() {
754 return 0;
755 },
756
757 /**
758 * @return {number}
759 */
760 minimumRowHeight() {
761 return 0;
762 },
763
764 /**
765 * @param {number} index
766 * @return {?Console.ConsoleViewportElement}
767 */
768 itemElement(index) {
769 return null;
770 }
771};
772
773/**
774 * @interface
775 */
776Console.ConsoleViewportElement = function() {};
777Console.ConsoleViewportElement.prototype = {
778 willHide() {},
779
780 wasShown() {},
781
782 /**
783 * @return {!Element}
784 */
785 element() {},
786};