blob: ae47b5c36a31e1671c98c8b5cc7799589aee5877 [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);
Pavel Feldmandb310912019-01-30 00:31:2061 this._contentElement.addEventListener('focusin', this._onFocusIn.bind(this), false);
62 this._contentElement.addEventListener('focusout', this._onFocusOut.bind(this), false);
63 this._contentElement.addEventListener('keydown', this._onKeyDown.bind(this), false);
Erik Luo39452ff2018-09-01 01:08:0764 this._virtualSelectedIndex = -1;
Erik Luob5bfff42018-09-20 02:52:3965 this._contentElement.tabIndex = -1;
Blink Reformat4c46d092018-04-07 15:32:3766
67 this._firstActiveIndex = -1;
68 this._lastActiveIndex = -1;
69 this._renderedItems = [];
70 this._anchorSelection = null;
71 this._headSelection = null;
72 this._itemCount = 0;
73 this._cumulativeHeights = new Int32Array(0);
74 this._muteCopyHandler = false;
75
76 // Listen for any changes to descendants and trigger a refresh. This ensures
77 // that items updated asynchronously will not break stick-to-bottom behavior
78 // if they change the scroll height.
79 this._observer = new MutationObserver(this.refresh.bind(this));
80 this._observerConfig = {childList: true, subtree: true};
81 }
82
83 /**
84 * @return {boolean}
85 */
86 stickToBottom() {
87 return this._stickToBottom;
88 }
89
90 /**
91 * @param {boolean} value
92 */
93 setStickToBottom(value) {
94 this._stickToBottom = value;
95 if (this._stickToBottom)
96 this._observer.observe(this._contentElement, this._observerConfig);
97 else
98 this._observer.disconnect();
99 }
100
Erik Luoad6c91c2018-12-06 03:28:42101 /**
102 * @return {boolean}
103 */
104 hasVirtualSelection() {
105 return this._virtualSelectedIndex !== -1;
106 }
107
Blink Reformat4c46d092018-04-07 15:32:37108 copyWithStyles() {
109 this._muteCopyHandler = true;
110 this.element.ownerDocument.execCommand('copy');
111 this._muteCopyHandler = false;
112 }
113
114 /**
115 * @param {!Event} event
116 */
117 _onCopy(event) {
118 if (this._muteCopyHandler)
119 return;
120 const text = this._selectedText();
121 if (!text)
122 return;
123 event.preventDefault();
124 event.clipboardData.setData('text/plain', text);
125 }
126
127 /**
128 * @param {!Event} event
129 */
Erik Luo39452ff2018-09-01 01:08:07130 _onFocusIn(event) {
Erik Luob5bfff42018-09-20 02:52:39131 const renderedIndex = this._renderedItems.findIndex(item => item.element().isSelfOrAncestor(event.target));
132 if (renderedIndex !== -1)
133 this._virtualSelectedIndex = this._firstActiveIndex + renderedIndex;
Erik Luofc6a6302018-11-02 06:48:52134 let focusLastChild = false;
Erik Luo39452ff2018-09-01 01:08:07135 // Make default selection when moving from external (e.g. prompt) to the container.
136 if (this._virtualSelectedIndex === -1 && this._isOutsideViewport(/** @type {?Element} */ (event.relatedTarget)) &&
Erik Luoad6c91c2018-12-06 03:28:42137 event.target === this._contentElement && this._itemCount) {
Erik Luofc6a6302018-11-02 06:48:52138 focusLastChild = true;
Erik Luo39452ff2018-09-01 01:08:07139 this._virtualSelectedIndex = this._itemCount - 1;
Erik Luo840be6b2018-12-03 20:54:27140
141 // Update stick to bottom before scrolling into view.
142 this.refresh();
143 this.scrollItemIntoView(this._virtualSelectedIndex);
Erik Luofc6a6302018-11-02 06:48:52144 }
145 this._updateFocusedItem(focusLastChild);
Erik Luo39452ff2018-09-01 01:08:07146 }
147
148 /**
149 * @param {!Event} event
150 */
151 _onFocusOut(event) {
152 // Remove selection when focus moves to external location (e.g. prompt).
153 if (this._isOutsideViewport(/** @type {?Element} */ (event.relatedTarget)))
154 this._virtualSelectedIndex = -1;
155 this._updateFocusedItem();
156 }
157
158 /**
159 * @param {?Element} element
160 * @return {boolean}
161 */
162 _isOutsideViewport(element) {
Erik Luob5bfff42018-09-20 02:52:39163 return !!element && !element.isSelfOrDescendant(this._contentElement);
Erik Luo39452ff2018-09-01 01:08:07164 }
165
166 /**
167 * @param {!Event} event
168 */
Blink Reformat4c46d092018-04-07 15:32:37169 _onDragStart(event) {
170 const text = this._selectedText();
171 if (!text)
172 return false;
173 event.dataTransfer.clearData();
174 event.dataTransfer.setData('text/plain', text);
175 event.dataTransfer.effectAllowed = 'copy';
176 return true;
177 }
178
179 /**
Erik Luo39452ff2018-09-01 01:08:07180 * @param {!Event} event
181 */
182 _onKeyDown(event) {
Erik Luob5bfff42018-09-20 02:52:39183 if (UI.isEditing() || !this._itemCount || event.shiftKey)
Erik Luo39452ff2018-09-01 01:08:07184 return;
Erik Luo0b8282e2018-10-08 20:37:46185 let isArrowUp = false;
Erik Luo39452ff2018-09-01 01:08:07186 switch (event.key) {
187 case 'ArrowUp':
Erik Luo0b8282e2018-10-08 20:37:46188 if (this._virtualSelectedIndex > 0) {
189 isArrowUp = true;
190 this._virtualSelectedIndex--;
191 } else {
192 return;
193 }
Erik Luo39452ff2018-09-01 01:08:07194 break;
195 case 'ArrowDown':
Erik Luo0b8282e2018-10-08 20:37:46196 if (this._virtualSelectedIndex < this._itemCount - 1)
197 this._virtualSelectedIndex++;
198 else
199 return;
Erik Luo39452ff2018-09-01 01:08:07200 break;
201 case 'Home':
202 this._virtualSelectedIndex = 0;
203 break;
204 case 'End':
205 this._virtualSelectedIndex = this._itemCount - 1;
206 break;
207 default:
208 return;
209 }
210 event.consume(true);
211 this.scrollItemIntoView(this._virtualSelectedIndex);
Erik Luo0b8282e2018-10-08 20:37:46212 this._updateFocusedItem(isArrowUp);
Erik Luo39452ff2018-09-01 01:08:07213 }
214
Erik Luo0b8282e2018-10-08 20:37:46215 /**
216 * @param {boolean=} focusLastChild
217 */
218 _updateFocusedItem(focusLastChild) {
Erik Luo39452ff2018-09-01 01:08:07219 const selectedElement = this.renderedElementAt(this._virtualSelectedIndex);
220 const changed = this._lastSelectedElement !== selectedElement;
Erik Luob5bfff42018-09-20 02:52:39221 const containerHasFocus = this._contentElement === this.element.ownerDocument.deepActiveElement();
Erik Luo39452ff2018-09-01 01:08:07222 if (this._lastSelectedElement && changed)
223 this._lastSelectedElement.classList.remove('console-selected');
Erik Luo840be6b2018-12-03 20:54:27224 if (selectedElement && (focusLastChild || changed || containerHasFocus) && this.element.hasFocus()) {
Erik Luo39452ff2018-09-01 01:08:07225 selectedElement.classList.add('console-selected');
Erik Luob5bfff42018-09-20 02:52:39226 // Do not focus the message if something within holds focus (e.g. object).
Erik Luo840be6b2018-12-03 20:54:27227 if (focusLastChild) {
228 this.setStickToBottom(false);
229 this._renderedItems[this._virtualSelectedIndex - this._firstActiveIndex].focusLastChildOrSelf();
230 } else if (!selectedElement.hasFocus()) {
231 focusWithoutScroll(selectedElement);
Erik Luo0b8282e2018-10-08 20:37:46232 }
Erik Luo39452ff2018-09-01 01:08:07233 }
234 if (this._itemCount && !this._contentElement.hasFocus())
Erik Luob5bfff42018-09-20 02:52:39235 this._contentElement.tabIndex = 0;
Erik Luo39452ff2018-09-01 01:08:07236 else
Erik Luob5bfff42018-09-20 02:52:39237 this._contentElement.tabIndex = -1;
Erik Luo39452ff2018-09-01 01:08:07238 this._lastSelectedElement = selectedElement;
239
240 /**
241 * @suppress {checkTypes}
242 * @param {!Element} element
243 */
244 function focusWithoutScroll(element) {
245 // TODO(luoe): Closure has an outdated typedef for Element.prototype.focus.
246 element.focus({preventScroll: true});
247 }
248 }
249
250 /**
Blink Reformat4c46d092018-04-07 15:32:37251 * @return {!Element}
252 */
253 contentElement() {
254 return this._contentElement;
255 }
256
257 invalidate() {
258 delete this._cachedProviderElements;
259 this._itemCount = this._provider.itemCount();
Erik Luo39452ff2018-09-01 01:08:07260 if (this._virtualSelectedIndex > this._itemCount - 1)
261 this._virtualSelectedIndex = this._itemCount - 1;
Blink Reformat4c46d092018-04-07 15:32:37262 this._rebuildCumulativeHeights();
263 this.refresh();
264 }
265
266 /**
267 * @param {number} index
268 * @return {?Console.ConsoleViewportElement}
269 */
270 _providerElement(index) {
271 if (!this._cachedProviderElements)
272 this._cachedProviderElements = new Array(this._itemCount);
273 let element = this._cachedProviderElements[index];
274 if (!element) {
275 element = this._provider.itemElement(index);
276 this._cachedProviderElements[index] = element;
277 }
278 return element;
279 }
280
281 _rebuildCumulativeHeights() {
282 const firstActiveIndex = this._firstActiveIndex;
283 const lastActiveIndex = this._lastActiveIndex;
284 let height = 0;
285 this._cumulativeHeights = new Int32Array(this._itemCount);
286 for (let i = 0; i < this._itemCount; ++i) {
287 if (firstActiveIndex <= i && i - firstActiveIndex < this._renderedItems.length && i <= lastActiveIndex)
288 height += this._renderedItems[i - firstActiveIndex].element().offsetHeight;
289 else
290 height += this._provider.fastHeight(i);
291 this._cumulativeHeights[i] = height;
292 }
293 }
294
295 _rebuildCumulativeHeightsIfNeeded() {
Erik Luo4b002322018-07-30 21:23:31296 let totalCachedHeight = 0;
297 let totalMeasuredHeight = 0;
Blink Reformat4c46d092018-04-07 15:32:37298 // Check whether current items in DOM have changed heights. Tolerate 1-pixel
299 // error due to double-to-integer rounding errors.
300 for (let i = 0; i < this._renderedItems.length; ++i) {
301 const cachedItemHeight = this._cachedItemHeight(this._firstActiveIndex + i);
Erik Luo4b002322018-07-30 21:23:31302 const measuredHeight = this._renderedItems[i].element().offsetHeight;
303 if (Math.abs(cachedItemHeight - measuredHeight) > 1) {
Blink Reformat4c46d092018-04-07 15:32:37304 this._rebuildCumulativeHeights();
Erik Luo4b002322018-07-30 21:23:31305 return;
306 }
307 totalMeasuredHeight += measuredHeight;
308 totalCachedHeight += cachedItemHeight;
309 if (Math.abs(totalCachedHeight - totalMeasuredHeight) > 1) {
310 this._rebuildCumulativeHeights();
311 return;
Blink Reformat4c46d092018-04-07 15:32:37312 }
313 }
314 }
315
316 /**
317 * @param {number} index
318 * @return {number}
319 */
320 _cachedItemHeight(index) {
321 return index === 0 ? this._cumulativeHeights[0] :
322 this._cumulativeHeights[index] - this._cumulativeHeights[index - 1];
323 }
324
325 /**
326 * @param {?Selection} selection
327 * @suppressGlobalPropertiesCheck
328 */
329 _isSelectionBackwards(selection) {
330 if (!selection || !selection.rangeCount)
331 return false;
332 const range = document.createRange();
333 range.setStart(selection.anchorNode, selection.anchorOffset);
334 range.setEnd(selection.focusNode, selection.focusOffset);
335 return range.collapsed;
336 }
337
338 /**
339 * @param {number} itemIndex
340 * @param {!Node} node
341 * @param {number} offset
342 * @return {!{item: number, node: !Node, offset: number}}
343 */
344 _createSelectionModel(itemIndex, node, offset) {
345 return {item: itemIndex, node: node, offset: offset};
346 }
347
348 /**
349 * @param {?Selection} selection
350 */
351 _updateSelectionModel(selection) {
352 const range = selection && selection.rangeCount ? selection.getRangeAt(0) : null;
353 if (!range || selection.isCollapsed || !this.element.hasSelection()) {
354 this._headSelection = null;
355 this._anchorSelection = null;
356 return false;
357 }
358
359 let firstSelected = Number.MAX_VALUE;
360 let lastSelected = -1;
361
362 let hasVisibleSelection = false;
363 for (let i = 0; i < this._renderedItems.length; ++i) {
364 if (range.intersectsNode(this._renderedItems[i].element())) {
365 const index = i + this._firstActiveIndex;
366 firstSelected = Math.min(firstSelected, index);
367 lastSelected = Math.max(lastSelected, index);
368 hasVisibleSelection = true;
369 }
370 }
371 if (hasVisibleSelection) {
372 firstSelected =
373 this._createSelectionModel(firstSelected, /** @type {!Node} */ (range.startContainer), range.startOffset);
374 lastSelected =
375 this._createSelectionModel(lastSelected, /** @type {!Node} */ (range.endContainer), range.endOffset);
376 }
377 const topOverlap = range.intersectsNode(this._topGapElement) && this._topGapElement._active;
378 const bottomOverlap = range.intersectsNode(this._bottomGapElement) && this._bottomGapElement._active;
379 if (!topOverlap && !bottomOverlap && !hasVisibleSelection) {
380 this._headSelection = null;
381 this._anchorSelection = null;
382 return false;
383 }
384
385 if (!this._anchorSelection || !this._headSelection) {
386 this._anchorSelection = this._createSelectionModel(0, this.element, 0);
387 this._headSelection = this._createSelectionModel(this._itemCount - 1, this.element, this.element.children.length);
388 this._selectionIsBackward = false;
389 }
390
391 const isBackward = this._isSelectionBackwards(selection);
392 const startSelection = this._selectionIsBackward ? this._headSelection : this._anchorSelection;
393 const endSelection = this._selectionIsBackward ? this._anchorSelection : this._headSelection;
394 if (topOverlap && bottomOverlap && hasVisibleSelection) {
395 firstSelected = firstSelected.item < startSelection.item ? firstSelected : startSelection;
396 lastSelected = lastSelected.item > endSelection.item ? lastSelected : endSelection;
397 } else if (!hasVisibleSelection) {
398 firstSelected = startSelection;
399 lastSelected = endSelection;
400 } else if (topOverlap) {
401 firstSelected = isBackward ? this._headSelection : this._anchorSelection;
402 } else if (bottomOverlap) {
403 lastSelected = isBackward ? this._anchorSelection : this._headSelection;
404 }
405
406 if (isBackward) {
407 this._anchorSelection = lastSelected;
408 this._headSelection = firstSelected;
409 } else {
410 this._anchorSelection = firstSelected;
411 this._headSelection = lastSelected;
412 }
413 this._selectionIsBackward = isBackward;
414 return true;
415 }
416
417 /**
418 * @param {?Selection} selection
419 */
420 _restoreSelection(selection) {
421 let anchorElement = null;
422 let anchorOffset;
423 if (this._firstActiveIndex <= this._anchorSelection.item && this._anchorSelection.item <= this._lastActiveIndex) {
424 anchorElement = this._anchorSelection.node;
425 anchorOffset = this._anchorSelection.offset;
426 } else {
427 if (this._anchorSelection.item < this._firstActiveIndex)
428 anchorElement = this._topGapElement;
429 else if (this._anchorSelection.item > this._lastActiveIndex)
430 anchorElement = this._bottomGapElement;
431 anchorOffset = this._selectionIsBackward ? 1 : 0;
432 }
433
434 let headElement = null;
435 let headOffset;
436 if (this._firstActiveIndex <= this._headSelection.item && this._headSelection.item <= this._lastActiveIndex) {
437 headElement = this._headSelection.node;
438 headOffset = this._headSelection.offset;
439 } else {
440 if (this._headSelection.item < this._firstActiveIndex)
441 headElement = this._topGapElement;
442 else if (this._headSelection.item > this._lastActiveIndex)
443 headElement = this._bottomGapElement;
444 headOffset = this._selectionIsBackward ? 0 : 1;
445 }
446
447 selection.setBaseAndExtent(anchorElement, anchorOffset, headElement, headOffset);
448 }
449
450 refresh() {
451 this._observer.disconnect();
452 this._innerRefresh();
453 if (this._stickToBottom)
454 this._observer.observe(this._contentElement, this._observerConfig);
455 }
456
457 _innerRefresh() {
458 if (!this._visibleHeight())
459 return; // Do nothing for invisible controls.
460
461 if (!this._itemCount) {
462 for (let i = 0; i < this._renderedItems.length; ++i)
463 this._renderedItems[i].willHide();
464 this._renderedItems = [];
465 this._contentElement.removeChildren();
466 this._topGapElement.style.height = '0px';
467 this._bottomGapElement.style.height = '0px';
468 this._firstActiveIndex = -1;
469 this._lastActiveIndex = -1;
Pavel Feldmandb310912019-01-30 00:31:20470 this._updateFocusedItem();
Blink Reformat4c46d092018-04-07 15:32:37471 return;
472 }
473
474 const selection = this.element.getComponentSelection();
475 const shouldRestoreSelection = this._updateSelectionModel(selection);
476
477 const visibleFrom = this.element.scrollTop;
478 const visibleHeight = this._visibleHeight();
479 const activeHeight = visibleHeight * 2;
480 this._rebuildCumulativeHeightsIfNeeded();
481
482 // When the viewport is scrolled to the bottom, using the cumulative heights estimate is not
483 // precise enough to determine next visible indices. This stickToBottom check avoids extra
484 // calls to refresh in those cases.
485 if (this._stickToBottom) {
486 this._firstActiveIndex =
487 Math.max(this._itemCount - Math.ceil(activeHeight / this._provider.minimumRowHeight()), 0);
488 this._lastActiveIndex = this._itemCount - 1;
489 } else {
490 this._firstActiveIndex =
491 Math.max(this._cumulativeHeights.lowerBound(visibleFrom + 1 - (activeHeight - visibleHeight) / 2), 0);
492 // Proactively render more rows in case some of them will be collapsed without triggering refresh. @see crbug.com/390169
493 this._lastActiveIndex = this._firstActiveIndex + Math.ceil(activeHeight / this._provider.minimumRowHeight()) - 1;
494 this._lastActiveIndex = Math.min(this._lastActiveIndex, this._itemCount - 1);
495 }
496
497 const topGapHeight = this._cumulativeHeights[this._firstActiveIndex - 1] || 0;
498 const bottomGapHeight =
499 this._cumulativeHeights[this._cumulativeHeights.length - 1] - this._cumulativeHeights[this._lastActiveIndex];
500
501 /**
502 * @this {Console.ConsoleViewport}
503 */
504 function prepare() {
505 this._topGapElement.style.height = topGapHeight + 'px';
506 this._bottomGapElement.style.height = bottomGapHeight + 'px';
507 this._topGapElement._active = !!topGapHeight;
508 this._bottomGapElement._active = !!bottomGapHeight;
509 this._contentElement.style.setProperty('height', '10000000px');
510 }
511
512 this._partialViewportUpdate(prepare.bind(this));
513 this._contentElement.style.removeProperty('height');
514 // Should be the last call in the method as it might force layout.
515 if (shouldRestoreSelection)
516 this._restoreSelection(selection);
517 if (this._stickToBottom)
518 this.element.scrollTop = 10000000;
519 }
520
521 /**
522 * @param {function()} prepare
523 */
524 _partialViewportUpdate(prepare) {
525 const itemsToRender = new Set();
526 for (let i = this._firstActiveIndex; i <= this._lastActiveIndex; ++i)
527 itemsToRender.add(this._providerElement(i));
528 const willBeHidden = this._renderedItems.filter(item => !itemsToRender.has(item));
529 for (let i = 0; i < willBeHidden.length; ++i)
530 willBeHidden[i].willHide();
531 prepare();
Erik Luo39452ff2018-09-01 01:08:07532 let hadFocus = false;
533 for (let i = 0; i < willBeHidden.length; ++i) {
Pavel Feldmandb310912019-01-30 00:31:20534 hadFocus = hadFocus || willBeHidden[i].element().hasFocus();
Blink Reformat4c46d092018-04-07 15:32:37535 willBeHidden[i].element().remove();
Erik Luo39452ff2018-09-01 01:08:07536 }
Blink Reformat4c46d092018-04-07 15:32:37537
538 const wasShown = [];
539 let anchor = this._contentElement.firstChild;
540 for (const viewportElement of itemsToRender) {
541 const element = viewportElement.element();
542 if (element !== anchor) {
543 const shouldCallWasShown = !element.parentElement;
544 if (shouldCallWasShown)
545 wasShown.push(viewportElement);
546 this._contentElement.insertBefore(element, anchor);
547 } else {
548 anchor = anchor.nextSibling;
549 }
550 }
551 for (let i = 0; i < wasShown.length; ++i)
552 wasShown[i].wasShown();
553 this._renderedItems = Array.from(itemsToRender);
Erik Luo39452ff2018-09-01 01:08:07554
Pavel Feldmandb310912019-01-30 00:31:20555 if (hadFocus)
556 this._contentElement.focus();
557 this._updateFocusedItem();
Blink Reformat4c46d092018-04-07 15:32:37558 }
559
560 /**
561 * @return {?string}
562 */
563 _selectedText() {
564 this._updateSelectionModel(this.element.getComponentSelection());
565 if (!this._headSelection || !this._anchorSelection)
566 return null;
567
568 let startSelection = null;
569 let endSelection = null;
570 if (this._selectionIsBackward) {
571 startSelection = this._headSelection;
572 endSelection = this._anchorSelection;
573 } else {
574 startSelection = this._anchorSelection;
575 endSelection = this._headSelection;
576 }
577
578 const textLines = [];
579 for (let i = startSelection.item; i <= endSelection.item; ++i) {
580 const element = this._providerElement(i).element();
581 const lineContent = element.childTextNodes().map(Components.Linkifier.untruncatedNodeText).join('');
582 textLines.push(lineContent);
583 }
584
585 const endSelectionElement = this._providerElement(endSelection.item).element();
586 if (endSelection.node && endSelection.node.isSelfOrDescendant(endSelectionElement)) {
587 const itemTextOffset = this._textOffsetInNode(endSelectionElement, endSelection.node, endSelection.offset);
588 textLines[textLines.length - 1] = textLines.peekLast().substring(0, itemTextOffset);
589 }
590
591 const startSelectionElement = this._providerElement(startSelection.item).element();
592 if (startSelection.node && startSelection.node.isSelfOrDescendant(startSelectionElement)) {
593 const itemTextOffset = this._textOffsetInNode(startSelectionElement, startSelection.node, startSelection.offset);
594 textLines[0] = textLines[0].substring(itemTextOffset);
595 }
596
597 return textLines.join('\n');
598 }
599
600 /**
601 * @param {!Element} itemElement
602 * @param {!Node} selectionNode
603 * @param {number} offset
604 * @return {number}
605 */
606 _textOffsetInNode(itemElement, selectionNode, offset) {
607 // If the selectionNode is not a TextNode, we may need to convert a child offset into a character offset.
608 if (selectionNode.nodeType !== Node.TEXT_NODE) {
609 if (offset < selectionNode.childNodes.length) {
610 selectionNode = /** @type {!Node} */ (selectionNode.childNodes.item(offset));
611 offset = 0;
612 } else {
613 offset = selectionNode.textContent.length;
614 }
615 }
616
617 let chars = 0;
618 let node = itemElement;
619 while ((node = node.traverseNextNode(itemElement)) && node !== selectionNode) {
620 if (node.nodeType !== Node.TEXT_NODE || node.parentElement.nodeName === 'STYLE' ||
621 node.parentElement.nodeName === 'SCRIPT')
622 continue;
623 chars += Components.Linkifier.untruncatedNodeText(node).length;
624 }
625 // If the selected node text was truncated, treat any non-zero offset as the full length.
626 const untruncatedContainerLength = Components.Linkifier.untruncatedNodeText(selectionNode).length;
627 if (offset > 0 && untruncatedContainerLength !== selectionNode.textContent.length)
628 offset = untruncatedContainerLength;
629 return chars + offset;
630 }
631
632 /**
633 * @param {!Event} event
634 */
635 _onScroll(event) {
636 this.refresh();
637 }
638
639 /**
640 * @return {number}
641 */
642 firstVisibleIndex() {
643 if (!this._cumulativeHeights.length)
644 return -1;
645 this._rebuildCumulativeHeightsIfNeeded();
646 return this._cumulativeHeights.lowerBound(this.element.scrollTop + 1);
647 }
648
649 /**
650 * @return {number}
651 */
652 lastVisibleIndex() {
653 if (!this._cumulativeHeights.length)
654 return -1;
655 this._rebuildCumulativeHeightsIfNeeded();
656 const scrollBottom = this.element.scrollTop + this.element.clientHeight;
657 const right = this._itemCount - 1;
658 return this._cumulativeHeights.lowerBound(scrollBottom, undefined, undefined, right);
659 }
660
661 /**
662 * @return {?Element}
663 */
664 renderedElementAt(index) {
Erik Luo39452ff2018-09-01 01:08:07665 if (index === -1 || index < this._firstActiveIndex || index > this._lastActiveIndex)
Blink Reformat4c46d092018-04-07 15:32:37666 return null;
667 return this._renderedItems[index - this._firstActiveIndex].element();
668 }
669
670 /**
671 * @param {number} index
672 * @param {boolean=} makeLast
673 */
674 scrollItemIntoView(index, makeLast) {
675 const firstVisibleIndex = this.firstVisibleIndex();
676 const lastVisibleIndex = this.lastVisibleIndex();
677 if (index > firstVisibleIndex && index < lastVisibleIndex)
678 return;
Erik Luo4b002322018-07-30 21:23:31679 // If the prompt is visible, then the last item must be fully on screen.
680 if (index === lastVisibleIndex && this._cumulativeHeights[index] <= this.element.scrollTop + this._visibleHeight())
681 return;
Blink Reformat4c46d092018-04-07 15:32:37682 if (makeLast)
683 this.forceScrollItemToBeLast(index);
684 else if (index <= firstVisibleIndex)
685 this.forceScrollItemToBeFirst(index);
686 else if (index >= lastVisibleIndex)
687 this.forceScrollItemToBeLast(index);
688 }
689
690 /**
691 * @param {number} index
692 */
693 forceScrollItemToBeFirst(index) {
694 console.assert(index >= 0 && index < this._itemCount, 'Cannot scroll item at invalid index');
695 this.setStickToBottom(false);
696 this._rebuildCumulativeHeightsIfNeeded();
697 this.element.scrollTop = index > 0 ? this._cumulativeHeights[index - 1] : 0;
698 if (this.element.isScrolledToBottom())
699 this.setStickToBottom(true);
700 this.refresh();
Erik Luo4b002322018-07-30 21:23:31701 // After refresh, the item is in DOM, but may not be visible (items above were larger than expected).
702 this.renderedElementAt(index).scrollIntoView(true /* alignTop */);
Blink Reformat4c46d092018-04-07 15:32:37703 }
704
705 /**
706 * @param {number} index
707 */
708 forceScrollItemToBeLast(index) {
709 console.assert(index >= 0 && index < this._itemCount, 'Cannot scroll item at invalid index');
710 this.setStickToBottom(false);
711 this._rebuildCumulativeHeightsIfNeeded();
712 this.element.scrollTop = this._cumulativeHeights[index] - this._visibleHeight();
713 if (this.element.isScrolledToBottom())
714 this.setStickToBottom(true);
715 this.refresh();
Erik Luo4b002322018-07-30 21:23:31716 // After refresh, the item is in DOM, but may not be visible (items above were larger than expected).
717 this.renderedElementAt(index).scrollIntoView(false /* alignTop */);
Blink Reformat4c46d092018-04-07 15:32:37718 }
719
720 /**
721 * @return {number}
722 */
723 _visibleHeight() {
724 // Use offsetHeight instead of clientHeight to avoid being affected by horizontal scroll.
725 return this.element.offsetHeight;
726 }
727};
728
729/**
730 * @interface
731 */
732Console.ConsoleViewportProvider = function() {};
733
734Console.ConsoleViewportProvider.prototype = {
735 /**
736 * @param {number} index
737 * @return {number}
738 */
739 fastHeight(index) {
740 return 0;
741 },
742
743 /**
744 * @return {number}
745 */
746 itemCount() {
747 return 0;
748 },
749
750 /**
751 * @return {number}
752 */
753 minimumRowHeight() {
754 return 0;
755 },
756
757 /**
758 * @param {number} index
759 * @return {?Console.ConsoleViewportElement}
760 */
761 itemElement(index) {
762 return null;
763 }
764};
765
766/**
767 * @interface
768 */
769Console.ConsoleViewportElement = function() {};
770Console.ConsoleViewportElement.prototype = {
771 willHide() {},
772
773 wasShown() {},
774
775 /**
776 * @return {!Element}
777 */
778 element() {},
779};