Correctly determines visiblity in additional document

Bug: 1467464
Change-Id: I5cbd3279e131f7da6b19454ba8036371218cf3a9
Reviewed-on: https://chromium-review.googlesource.com/c/devtools/devtools-frontend/+/5062916
Reviewed-by: Simon Zünd <szuend@chromium.org>
Commit-Queue: Danil Somsikov <dsv@chromium.org>
Auto-Submit: Danil Somsikov <dsv@chromium.org>
diff --git a/front_end/ui/visual_logging/LoggingDriver.ts b/front_end/ui/visual_logging/LoggingDriver.ts
index cba90de..e68d43b 100644
--- a/front_end/ui/visual_logging/LoggingDriver.ts
+++ b/front_end/ui/visual_logging/LoggingDriver.ts
@@ -105,11 +105,15 @@
   const startTime = performance.now();
   const {loggables, shadowRoots} = getDomState(documents);
   const visibleElements: Element[] = [];
-  const viewportRect = new DOMRect(0, 0, document.documentElement.clientWidth, document.documentElement.clientHeight);
+  const viewportRects = new Map<Document, DOMRect>();
   observeMutations(shadowRoots);
   for (const {element, parent} of loggables) {
     const loggingState = getOrCreateLoggingState(element, getLoggingConfig(element), parent);
     if (!loggingState.impressionLogged) {
+      const ownerDocument = element.ownerDocument;
+      const viewportRect = viewportRects.get(ownerDocument) ||
+          new DOMRect(0, 0, ownerDocument.defaultView?.innerWidth || 0, ownerDocument.defaultView?.innerHeight || 0);
+      viewportRects.set(ownerDocument, viewportRect);
       if (isVisible(element, viewportRect)) {
         visibleElements.push(element);
         loggingState.impressionLogged = true;
diff --git a/test/unittests/front_end/ui/visual_logging/LoggingDriver_test.ts b/test/unittests/front_end/ui/visual_logging/LoggingDriver_test.ts
index e35285d..4db3bf8 100644
--- a/test/unittests/front_end/ui/visual_logging/LoggingDriver_test.ts
+++ b/test/unittests/front_end/ui/visual_logging/LoggingDriver_test.ts
@@ -134,6 +134,24 @@
     await assertImpressionRecordedDeferred();
   });
 
+  it('correctly determines visiblity in additional document', async () => {
+    const iframe = document.createElement('iframe') as HTMLIFrameElement;
+    renderElementIntoDOM(iframe);
+    iframe.style.width = '100px';
+    iframe.style.height = '100px';
+    iframe.width = '100';
+    iframe.height = '100';
+    const iframeDocument = iframe.contentDocument;
+    assertNotNullOrUndefined(iframeDocument);
+    iframeDocument.body.innerHTML =  // Second div should not be out of viewport and not logged
+        `<div style="width:150px;height:150px"></div>
+         <div jslog="TreeItem" style="width:150px;height:150px"></div>`;
+
+    await VisualLoggingTesting.LoggingDriver.startLogging({domProcessingThrottler: throttler});
+    await VisualLoggingTesting.LoggingDriver.addDocument(iframeDocument);
+    assert.isFalse(recordImpression.called);
+  });
+
   it('logs clicks', async () => {
     addLoggableElements();
     await VisualLoggingTesting.LoggingDriver.startLogging();