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