blob: f1ea217ef04d0f045b1a38a8653004c4a7e810f5 [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
104 copyWithStyles() {
105 this._muteCopyHandler = true;
106 this.element.ownerDocument.execCommand('copy');
107 this._muteCopyHandler = false;
108 }
109
110 /**
111 * @param {!Event} event
112 */
113 _onCopy(event) {
114 if (this._muteCopyHandler)
115 return;
116 const text = this._selectedText();
117 if (!text)
118 return;
119 event.preventDefault();
120 event.clipboardData.setData('text/plain', text);
121 }
122
123 /**
124 * @param {!Event} event
125 */
Erik Luo39452ff2018-09-01 01:08:07126 _onFocusIn(event) {
Erik Luob5bfff42018-09-20 02:52:39127 const renderedIndex = this._renderedItems.findIndex(item => item.element().isSelfOrAncestor(event.target));
128 if (renderedIndex !== -1)
129 this._virtualSelectedIndex = this._firstActiveIndex + renderedIndex;
Erik Luo39452ff2018-09-01 01:08:07130 // Make default selection when moving from external (e.g. prompt) to the container.
131 if (this._virtualSelectedIndex === -1 && this._isOutsideViewport(/** @type {?Element} */ (event.relatedTarget)) &&
Erik Luob5bfff42018-09-20 02:52:39132 event.target === this._contentElement)
Erik Luo39452ff2018-09-01 01:08:07133 this._virtualSelectedIndex = this._itemCount - 1;
134 this._updateFocusedItem();
135 }
136
137 /**
138 * @param {!Event} event
139 */
140 _onFocusOut(event) {
141 // Remove selection when focus moves to external location (e.g. prompt).
142 if (this._isOutsideViewport(/** @type {?Element} */ (event.relatedTarget)))
143 this._virtualSelectedIndex = -1;
144 this._updateFocusedItem();
145 }
146
147 /**
148 * @param {?Element} element
149 * @return {boolean}
150 */
151 _isOutsideViewport(element) {
Erik Luob5bfff42018-09-20 02:52:39152 return !!element && !element.isSelfOrDescendant(this._contentElement);
Erik Luo39452ff2018-09-01 01:08:07153 }
154
155 /**
156 * @param {!Event} event
157 */
Blink Reformat4c46d092018-04-07 15:32:37158 _onDragStart(event) {
159 const text = this._selectedText();
160 if (!text)
161 return false;
162 event.dataTransfer.clearData();
163 event.dataTransfer.setData('text/plain', text);
164 event.dataTransfer.effectAllowed = 'copy';
165 return true;
166 }
167
168 /**
Erik Luo39452ff2018-09-01 01:08:07169 * @param {!Event} event
170 */
171 _onKeyDown(event) {
Erik Luob5bfff42018-09-20 02:52:39172 if (UI.isEditing() || !this._itemCount || event.shiftKey)
Erik Luo39452ff2018-09-01 01:08:07173 return;
Erik Luo0b8282e2018-10-08 20:37:46174 let isArrowUp = false;
Erik Luo39452ff2018-09-01 01:08:07175 switch (event.key) {
176 case 'ArrowUp':
Erik Luo0b8282e2018-10-08 20:37:46177 if (this._virtualSelectedIndex > 0) {
178 isArrowUp = true;
179 this._virtualSelectedIndex--;
180 } else {
181 return;
182 }
Erik Luo39452ff2018-09-01 01:08:07183 break;
184 case 'ArrowDown':
Erik Luo0b8282e2018-10-08 20:37:46185 if (this._virtualSelectedIndex < this._itemCount - 1)
186 this._virtualSelectedIndex++;
187 else
188 return;
Erik Luo39452ff2018-09-01 01:08:07189 break;
190 case 'Home':
191 this._virtualSelectedIndex = 0;
192 break;
193 case 'End':
194 this._virtualSelectedIndex = this._itemCount - 1;
195 break;
196 default:
197 return;
198 }
199 event.consume(true);
200 this.scrollItemIntoView(this._virtualSelectedIndex);
Erik Luo0b8282e2018-10-08 20:37:46201 this._updateFocusedItem(isArrowUp);
Erik Luo39452ff2018-09-01 01:08:07202 }
203
Erik Luo0b8282e2018-10-08 20:37:46204 /**
205 * @param {boolean=} focusLastChild
206 */
207 _updateFocusedItem(focusLastChild) {
Erik Luo39452ff2018-09-01 01:08:07208 const selectedElement = this.renderedElementAt(this._virtualSelectedIndex);
209 const changed = this._lastSelectedElement !== selectedElement;
Erik Luob5bfff42018-09-20 02:52:39210 const containerHasFocus = this._contentElement === this.element.ownerDocument.deepActiveElement();
Erik Luo39452ff2018-09-01 01:08:07211 if (this._lastSelectedElement && changed)
212 this._lastSelectedElement.classList.remove('console-selected');
Erik Luo0b8282e2018-10-08 20:37:46213 if (selectedElement && (changed || containerHasFocus) && this.element.hasFocus()) {
Erik Luo39452ff2018-09-01 01:08:07214 selectedElement.classList.add('console-selected');
Erik Luob5bfff42018-09-20 02:52:39215 // Do not focus the message if something within holds focus (e.g. object).
Erik Luo0b8282e2018-10-08 20:37:46216 if (!selectedElement.hasFocus()) {
217 if (focusLastChild)
218 this._renderedItems[this._virtualSelectedIndex - this._firstActiveIndex].focusLastChildOrSelf();
219 else
220 focusWithoutScroll(selectedElement);
221 }
Erik Luo39452ff2018-09-01 01:08:07222 }
223 if (this._itemCount && !this._contentElement.hasFocus())
Erik Luob5bfff42018-09-20 02:52:39224 this._contentElement.tabIndex = 0;
Erik Luo39452ff2018-09-01 01:08:07225 else
Erik Luob5bfff42018-09-20 02:52:39226 this._contentElement.tabIndex = -1;
Erik Luo39452ff2018-09-01 01:08:07227 this._lastSelectedElement = selectedElement;
228
229 /**
230 * @suppress {checkTypes}
231 * @param {!Element} element
232 */
233 function focusWithoutScroll(element) {
234 // TODO(luoe): Closure has an outdated typedef for Element.prototype.focus.
235 element.focus({preventScroll: true});
236 }
237 }
238
239 /**
Blink Reformat4c46d092018-04-07 15:32:37240 * @return {!Element}
241 */
242 contentElement() {
243 return this._contentElement;
244 }
245
246 invalidate() {
247 delete this._cachedProviderElements;
248 this._itemCount = this._provider.itemCount();
Erik Luo39452ff2018-09-01 01:08:07249 if (this._virtualSelectedIndex > this._itemCount - 1)
250 this._virtualSelectedIndex = this._itemCount - 1;
Blink Reformat4c46d092018-04-07 15:32:37251 this._rebuildCumulativeHeights();
252 this.refresh();
253 }
254
255 /**
256 * @param {number} index
257 * @return {?Console.ConsoleViewportElement}
258 */
259 _providerElement(index) {
260 if (!this._cachedProviderElements)
261 this._cachedProviderElements = new Array(this._itemCount);
262 let element = this._cachedProviderElements[index];
263 if (!element) {
264 element = this._provider.itemElement(index);
265 this._cachedProviderElements[index] = element;
266 }
267 return element;
268 }
269
270 _rebuildCumulativeHeights() {
271 const firstActiveIndex = this._firstActiveIndex;
272 const lastActiveIndex = this._lastActiveIndex;
273 let height = 0;
274 this._cumulativeHeights = new Int32Array(this._itemCount);
275 for (let i = 0; i < this._itemCount; ++i) {
276 if (firstActiveIndex <= i && i - firstActiveIndex < this._renderedItems.length && i <= lastActiveIndex)
277 height += this._renderedItems[i - firstActiveIndex].element().offsetHeight;
278 else
279 height += this._provider.fastHeight(i);
280 this._cumulativeHeights[i] = height;
281 }
282 }
283
284 _rebuildCumulativeHeightsIfNeeded() {
Erik Luo4b002322018-07-30 21:23:31285 let totalCachedHeight = 0;
286 let totalMeasuredHeight = 0;
Blink Reformat4c46d092018-04-07 15:32:37287 // Check whether current items in DOM have changed heights. Tolerate 1-pixel
288 // error due to double-to-integer rounding errors.
289 for (let i = 0; i < this._renderedItems.length; ++i) {
290 const cachedItemHeight = this._cachedItemHeight(this._firstActiveIndex + i);
Erik Luo4b002322018-07-30 21:23:31291 const measuredHeight = this._renderedItems[i].element().offsetHeight;
292 if (Math.abs(cachedItemHeight - measuredHeight) > 1) {
Blink Reformat4c46d092018-04-07 15:32:37293 this._rebuildCumulativeHeights();
Erik Luo4b002322018-07-30 21:23:31294 return;
295 }
296 totalMeasuredHeight += measuredHeight;
297 totalCachedHeight += cachedItemHeight;
298 if (Math.abs(totalCachedHeight - totalMeasuredHeight) > 1) {
299 this._rebuildCumulativeHeights();
300 return;
Blink Reformat4c46d092018-04-07 15:32:37301 }
302 }
303 }
304
305 /**
306 * @param {number} index
307 * @return {number}
308 */
309 _cachedItemHeight(index) {
310 return index === 0 ? this._cumulativeHeights[0] :
311 this._cumulativeHeights[index] - this._cumulativeHeights[index - 1];
312 }
313
314 /**
315 * @param {?Selection} selection
316 * @suppressGlobalPropertiesCheck
317 */
318 _isSelectionBackwards(selection) {
319 if (!selection || !selection.rangeCount)
320 return false;
321 const range = document.createRange();
322 range.setStart(selection.anchorNode, selection.anchorOffset);
323 range.setEnd(selection.focusNode, selection.focusOffset);
324 return range.collapsed;
325 }
326
327 /**
328 * @param {number} itemIndex
329 * @param {!Node} node
330 * @param {number} offset
331 * @return {!{item: number, node: !Node, offset: number}}
332 */
333 _createSelectionModel(itemIndex, node, offset) {
334 return {item: itemIndex, node: node, offset: offset};
335 }
336
337 /**
338 * @param {?Selection} selection
339 */
340 _updateSelectionModel(selection) {
341 const range = selection && selection.rangeCount ? selection.getRangeAt(0) : null;
342 if (!range || selection.isCollapsed || !this.element.hasSelection()) {
343 this._headSelection = null;
344 this._anchorSelection = null;
345 return false;
346 }
347
348 let firstSelected = Number.MAX_VALUE;
349 let lastSelected = -1;
350
351 let hasVisibleSelection = false;
352 for (let i = 0; i < this._renderedItems.length; ++i) {
353 if (range.intersectsNode(this._renderedItems[i].element())) {
354 const index = i + this._firstActiveIndex;
355 firstSelected = Math.min(firstSelected, index);
356 lastSelected = Math.max(lastSelected, index);
357 hasVisibleSelection = true;
358 }
359 }
360 if (hasVisibleSelection) {
361 firstSelected =
362 this._createSelectionModel(firstSelected, /** @type {!Node} */ (range.startContainer), range.startOffset);
363 lastSelected =
364 this._createSelectionModel(lastSelected, /** @type {!Node} */ (range.endContainer), range.endOffset);
365 }
366 const topOverlap = range.intersectsNode(this._topGapElement) && this._topGapElement._active;
367 const bottomOverlap = range.intersectsNode(this._bottomGapElement) && this._bottomGapElement._active;
368 if (!topOverlap && !bottomOverlap && !hasVisibleSelection) {
369 this._headSelection = null;
370 this._anchorSelection = null;
371 return false;
372 }
373
374 if (!this._anchorSelection || !this._headSelection) {
375 this._anchorSelection = this._createSelectionModel(0, this.element, 0);
376 this._headSelection = this._createSelectionModel(this._itemCount - 1, this.element, this.element.children.length);
377 this._selectionIsBackward = false;
378 }
379
380 const isBackward = this._isSelectionBackwards(selection);
381 const startSelection = this._selectionIsBackward ? this._headSelection : this._anchorSelection;
382 const endSelection = this._selectionIsBackward ? this._anchorSelection : this._headSelection;
383 if (topOverlap && bottomOverlap && hasVisibleSelection) {
384 firstSelected = firstSelected.item < startSelection.item ? firstSelected : startSelection;
385 lastSelected = lastSelected.item > endSelection.item ? lastSelected : endSelection;
386 } else if (!hasVisibleSelection) {
387 firstSelected = startSelection;
388 lastSelected = endSelection;
389 } else if (topOverlap) {
390 firstSelected = isBackward ? this._headSelection : this._anchorSelection;
391 } else if (bottomOverlap) {
392 lastSelected = isBackward ? this._anchorSelection : this._headSelection;
393 }
394
395 if (isBackward) {
396 this._anchorSelection = lastSelected;
397 this._headSelection = firstSelected;
398 } else {
399 this._anchorSelection = firstSelected;
400 this._headSelection = lastSelected;
401 }
402 this._selectionIsBackward = isBackward;
403 return true;
404 }
405
406 /**
407 * @param {?Selection} selection
408 */
409 _restoreSelection(selection) {
410 let anchorElement = null;
411 let anchorOffset;
412 if (this._firstActiveIndex <= this._anchorSelection.item && this._anchorSelection.item <= this._lastActiveIndex) {
413 anchorElement = this._anchorSelection.node;
414 anchorOffset = this._anchorSelection.offset;
415 } else {
416 if (this._anchorSelection.item < this._firstActiveIndex)
417 anchorElement = this._topGapElement;
418 else if (this._anchorSelection.item > this._lastActiveIndex)
419 anchorElement = this._bottomGapElement;
420 anchorOffset = this._selectionIsBackward ? 1 : 0;
421 }
422
423 let headElement = null;
424 let headOffset;
425 if (this._firstActiveIndex <= this._headSelection.item && this._headSelection.item <= this._lastActiveIndex) {
426 headElement = this._headSelection.node;
427 headOffset = this._headSelection.offset;
428 } else {
429 if (this._headSelection.item < this._firstActiveIndex)
430 headElement = this._topGapElement;
431 else if (this._headSelection.item > this._lastActiveIndex)
432 headElement = this._bottomGapElement;
433 headOffset = this._selectionIsBackward ? 0 : 1;
434 }
435
436 selection.setBaseAndExtent(anchorElement, anchorOffset, headElement, headOffset);
437 }
438
439 refresh() {
440 this._observer.disconnect();
441 this._innerRefresh();
442 if (this._stickToBottom)
443 this._observer.observe(this._contentElement, this._observerConfig);
444 }
445
446 _innerRefresh() {
447 if (!this._visibleHeight())
448 return; // Do nothing for invisible controls.
449
450 if (!this._itemCount) {
451 for (let i = 0; i < this._renderedItems.length; ++i)
452 this._renderedItems[i].willHide();
453 this._renderedItems = [];
454 this._contentElement.removeChildren();
455 this._topGapElement.style.height = '0px';
456 this._bottomGapElement.style.height = '0px';
457 this._firstActiveIndex = -1;
458 this._lastActiveIndex = -1;
Erik Luo39452ff2018-09-01 01:08:07459 if (this._keyboardNavigationEnabled)
460 this._updateFocusedItem();
Blink Reformat4c46d092018-04-07 15:32:37461 return;
462 }
463
464 const selection = this.element.getComponentSelection();
465 const shouldRestoreSelection = this._updateSelectionModel(selection);
466
467 const visibleFrom = this.element.scrollTop;
468 const visibleHeight = this._visibleHeight();
469 const activeHeight = visibleHeight * 2;
470 this._rebuildCumulativeHeightsIfNeeded();
471
472 // When the viewport is scrolled to the bottom, using the cumulative heights estimate is not
473 // precise enough to determine next visible indices. This stickToBottom check avoids extra
474 // calls to refresh in those cases.
475 if (this._stickToBottom) {
476 this._firstActiveIndex =
477 Math.max(this._itemCount - Math.ceil(activeHeight / this._provider.minimumRowHeight()), 0);
478 this._lastActiveIndex = this._itemCount - 1;
479 } else {
480 this._firstActiveIndex =
481 Math.max(this._cumulativeHeights.lowerBound(visibleFrom + 1 - (activeHeight - visibleHeight) / 2), 0);
482 // Proactively render more rows in case some of them will be collapsed without triggering refresh. @see crbug.com/390169
483 this._lastActiveIndex = this._firstActiveIndex + Math.ceil(activeHeight / this._provider.minimumRowHeight()) - 1;
484 this._lastActiveIndex = Math.min(this._lastActiveIndex, this._itemCount - 1);
485 }
486
487 const topGapHeight = this._cumulativeHeights[this._firstActiveIndex - 1] || 0;
488 const bottomGapHeight =
489 this._cumulativeHeights[this._cumulativeHeights.length - 1] - this._cumulativeHeights[this._lastActiveIndex];
490
491 /**
492 * @this {Console.ConsoleViewport}
493 */
494 function prepare() {
495 this._topGapElement.style.height = topGapHeight + 'px';
496 this._bottomGapElement.style.height = bottomGapHeight + 'px';
497 this._topGapElement._active = !!topGapHeight;
498 this._bottomGapElement._active = !!bottomGapHeight;
499 this._contentElement.style.setProperty('height', '10000000px');
500 }
501
502 this._partialViewportUpdate(prepare.bind(this));
503 this._contentElement.style.removeProperty('height');
504 // Should be the last call in the method as it might force layout.
505 if (shouldRestoreSelection)
506 this._restoreSelection(selection);
507 if (this._stickToBottom)
508 this.element.scrollTop = 10000000;
509 }
510
511 /**
512 * @param {function()} prepare
513 */
514 _partialViewportUpdate(prepare) {
515 const itemsToRender = new Set();
516 for (let i = this._firstActiveIndex; i <= this._lastActiveIndex; ++i)
517 itemsToRender.add(this._providerElement(i));
518 const willBeHidden = this._renderedItems.filter(item => !itemsToRender.has(item));
519 for (let i = 0; i < willBeHidden.length; ++i)
520 willBeHidden[i].willHide();
521 prepare();
Erik Luo39452ff2018-09-01 01:08:07522 let hadFocus = false;
523 for (let i = 0; i < willBeHidden.length; ++i) {
524 if (this._keyboardNavigationEnabled)
525 hadFocus = hadFocus || willBeHidden[i].element().hasFocus();
Blink Reformat4c46d092018-04-07 15:32:37526 willBeHidden[i].element().remove();
Erik Luo39452ff2018-09-01 01:08:07527 }
Blink Reformat4c46d092018-04-07 15:32:37528
529 const wasShown = [];
530 let anchor = this._contentElement.firstChild;
531 for (const viewportElement of itemsToRender) {
532 const element = viewportElement.element();
533 if (element !== anchor) {
534 const shouldCallWasShown = !element.parentElement;
535 if (shouldCallWasShown)
536 wasShown.push(viewportElement);
537 this._contentElement.insertBefore(element, anchor);
538 } else {
539 anchor = anchor.nextSibling;
540 }
541 }
542 for (let i = 0; i < wasShown.length; ++i)
543 wasShown[i].wasShown();
544 this._renderedItems = Array.from(itemsToRender);
Erik Luo39452ff2018-09-01 01:08:07545
546 if (this._keyboardNavigationEnabled) {
547 if (hadFocus)
Erik Luob5bfff42018-09-20 02:52:39548 this._contentElement.focus();
Erik Luo39452ff2018-09-01 01:08:07549 this._updateFocusedItem();
550 }
Blink Reformat4c46d092018-04-07 15:32:37551 }
552
553 /**
554 * @return {?string}
555 */
556 _selectedText() {
557 this._updateSelectionModel(this.element.getComponentSelection());
558 if (!this._headSelection || !this._anchorSelection)
559 return null;
560
561 let startSelection = null;
562 let endSelection = null;
563 if (this._selectionIsBackward) {
564 startSelection = this._headSelection;
565 endSelection = this._anchorSelection;
566 } else {
567 startSelection = this._anchorSelection;
568 endSelection = this._headSelection;
569 }
570
571 const textLines = [];
572 for (let i = startSelection.item; i <= endSelection.item; ++i) {
573 const element = this._providerElement(i).element();
574 const lineContent = element.childTextNodes().map(Components.Linkifier.untruncatedNodeText).join('');
575 textLines.push(lineContent);
576 }
577
578 const endSelectionElement = this._providerElement(endSelection.item).element();
579 if (endSelection.node && endSelection.node.isSelfOrDescendant(endSelectionElement)) {
580 const itemTextOffset = this._textOffsetInNode(endSelectionElement, endSelection.node, endSelection.offset);
581 textLines[textLines.length - 1] = textLines.peekLast().substring(0, itemTextOffset);
582 }
583
584 const startSelectionElement = this._providerElement(startSelection.item).element();
585 if (startSelection.node && startSelection.node.isSelfOrDescendant(startSelectionElement)) {
586 const itemTextOffset = this._textOffsetInNode(startSelectionElement, startSelection.node, startSelection.offset);
587 textLines[0] = textLines[0].substring(itemTextOffset);
588 }
589
590 return textLines.join('\n');
591 }
592
593 /**
594 * @param {!Element} itemElement
595 * @param {!Node} selectionNode
596 * @param {number} offset
597 * @return {number}
598 */
599 _textOffsetInNode(itemElement, selectionNode, offset) {
600 // If the selectionNode is not a TextNode, we may need to convert a child offset into a character offset.
601 if (selectionNode.nodeType !== Node.TEXT_NODE) {
602 if (offset < selectionNode.childNodes.length) {
603 selectionNode = /** @type {!Node} */ (selectionNode.childNodes.item(offset));
604 offset = 0;
605 } else {
606 offset = selectionNode.textContent.length;
607 }
608 }
609
610 let chars = 0;
611 let node = itemElement;
612 while ((node = node.traverseNextNode(itemElement)) && node !== selectionNode) {
613 if (node.nodeType !== Node.TEXT_NODE || node.parentElement.nodeName === 'STYLE' ||
614 node.parentElement.nodeName === 'SCRIPT')
615 continue;
616 chars += Components.Linkifier.untruncatedNodeText(node).length;
617 }
618 // If the selected node text was truncated, treat any non-zero offset as the full length.
619 const untruncatedContainerLength = Components.Linkifier.untruncatedNodeText(selectionNode).length;
620 if (offset > 0 && untruncatedContainerLength !== selectionNode.textContent.length)
621 offset = untruncatedContainerLength;
622 return chars + offset;
623 }
624
625 /**
626 * @param {!Event} event
627 */
628 _onScroll(event) {
629 this.refresh();
630 }
631
632 /**
633 * @return {number}
634 */
635 firstVisibleIndex() {
636 if (!this._cumulativeHeights.length)
637 return -1;
638 this._rebuildCumulativeHeightsIfNeeded();
639 return this._cumulativeHeights.lowerBound(this.element.scrollTop + 1);
640 }
641
642 /**
643 * @return {number}
644 */
645 lastVisibleIndex() {
646 if (!this._cumulativeHeights.length)
647 return -1;
648 this._rebuildCumulativeHeightsIfNeeded();
649 const scrollBottom = this.element.scrollTop + this.element.clientHeight;
650 const right = this._itemCount - 1;
651 return this._cumulativeHeights.lowerBound(scrollBottom, undefined, undefined, right);
652 }
653
654 /**
655 * @return {?Element}
656 */
657 renderedElementAt(index) {
Erik Luo39452ff2018-09-01 01:08:07658 if (index === -1 || index < this._firstActiveIndex || index > this._lastActiveIndex)
Blink Reformat4c46d092018-04-07 15:32:37659 return null;
660 return this._renderedItems[index - this._firstActiveIndex].element();
661 }
662
663 /**
664 * @param {number} index
665 * @param {boolean=} makeLast
666 */
667 scrollItemIntoView(index, makeLast) {
668 const firstVisibleIndex = this.firstVisibleIndex();
669 const lastVisibleIndex = this.lastVisibleIndex();
670 if (index > firstVisibleIndex && index < lastVisibleIndex)
671 return;
Erik Luo4b002322018-07-30 21:23:31672 // If the prompt is visible, then the last item must be fully on screen.
673 if (index === lastVisibleIndex && this._cumulativeHeights[index] <= this.element.scrollTop + this._visibleHeight())
674 return;
Blink Reformat4c46d092018-04-07 15:32:37675 if (makeLast)
676 this.forceScrollItemToBeLast(index);
677 else if (index <= firstVisibleIndex)
678 this.forceScrollItemToBeFirst(index);
679 else if (index >= lastVisibleIndex)
680 this.forceScrollItemToBeLast(index);
681 }
682
683 /**
684 * @param {number} index
685 */
686 forceScrollItemToBeFirst(index) {
687 console.assert(index >= 0 && index < this._itemCount, 'Cannot scroll item at invalid index');
688 this.setStickToBottom(false);
689 this._rebuildCumulativeHeightsIfNeeded();
690 this.element.scrollTop = index > 0 ? this._cumulativeHeights[index - 1] : 0;
691 if (this.element.isScrolledToBottom())
692 this.setStickToBottom(true);
693 this.refresh();
Erik Luo4b002322018-07-30 21:23:31694 // After refresh, the item is in DOM, but may not be visible (items above were larger than expected).
695 this.renderedElementAt(index).scrollIntoView(true /* alignTop */);
Blink Reformat4c46d092018-04-07 15:32:37696 }
697
698 /**
699 * @param {number} index
700 */
701 forceScrollItemToBeLast(index) {
702 console.assert(index >= 0 && index < this._itemCount, 'Cannot scroll item at invalid index');
703 this.setStickToBottom(false);
704 this._rebuildCumulativeHeightsIfNeeded();
705 this.element.scrollTop = this._cumulativeHeights[index] - this._visibleHeight();
706 if (this.element.isScrolledToBottom())
707 this.setStickToBottom(true);
708 this.refresh();
Erik Luo4b002322018-07-30 21:23:31709 // After refresh, the item is in DOM, but may not be visible (items above were larger than expected).
710 this.renderedElementAt(index).scrollIntoView(false /* alignTop */);
Blink Reformat4c46d092018-04-07 15:32:37711 }
712
713 /**
714 * @return {number}
715 */
716 _visibleHeight() {
717 // Use offsetHeight instead of clientHeight to avoid being affected by horizontal scroll.
718 return this.element.offsetHeight;
719 }
720};
721
722/**
723 * @interface
724 */
725Console.ConsoleViewportProvider = function() {};
726
727Console.ConsoleViewportProvider.prototype = {
728 /**
729 * @param {number} index
730 * @return {number}
731 */
732 fastHeight(index) {
733 return 0;
734 },
735
736 /**
737 * @return {number}
738 */
739 itemCount() {
740 return 0;
741 },
742
743 /**
744 * @return {number}
745 */
746 minimumRowHeight() {
747 return 0;
748 },
749
750 /**
751 * @param {number} index
752 * @return {?Console.ConsoleViewportElement}
753 */
754 itemElement(index) {
755 return null;
756 }
757};
758
759/**
760 * @interface
761 */
762Console.ConsoleViewportElement = function() {};
763Console.ConsoleViewportElement.prototype = {
764 willHide() {},
765
766 wasShown() {},
767
768 /**
769 * @return {!Element}
770 */
771 element() {},
772};