Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(239)

Side by Side Diff: third_party/WebKit/Source/core/dom/IntersectionObserver.cpp

Issue 1559593002: Add root margin support for IntersectionObserver. (Closed) Base URL: https://chromium.googlesource.com/chromium/src@intersection-observer-no-root-margin
Patch Set: test expectation Created 4 years, 11 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
1 // Copyright 2016 The Chromium Authors. All rights reserved. 1 // Copyright 2016 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "core/dom/IntersectionObserver.h" 5 #include "core/dom/IntersectionObserver.h"
6 6
7 #include "bindings/core/v8/ExceptionState.h" 7 #include "bindings/core/v8/ExceptionState.h"
8 #include "core/css/parser/CSSParserTokenRange.h" 8 #include "core/css/parser/CSSParserTokenRange.h"
9 #include "core/css/parser/CSSTokenizer.h" 9 #include "core/css/parser/CSSTokenizer.h"
10 #include "core/dom/ElementIntersectionObserverData.h" 10 #include "core/dom/ElementIntersectionObserverData.h"
11 #include "core/dom/ExceptionCode.h" 11 #include "core/dom/ExceptionCode.h"
12 #include "core/dom/ExecutionContext.h" 12 #include "core/dom/ExecutionContext.h"
13 #include "core/dom/IntersectionObserverCallback.h" 13 #include "core/dom/IntersectionObserverCallback.h"
14 #include "core/dom/IntersectionObserverController.h" 14 #include "core/dom/IntersectionObserverController.h"
15 #include "core/dom/IntersectionObserverEntry.h" 15 #include "core/dom/IntersectionObserverEntry.h"
16 #include "core/dom/IntersectionObserverInit.h" 16 #include "core/dom/IntersectionObserverInit.h"
17 #include "core/html/HTMLFrameOwnerElement.h" 17 #include "core/html/HTMLFrameOwnerElement.h"
18 #include "core/layout/LayoutView.h" 18 #include "core/layout/LayoutView.h"
19 #include "platform/Timer.h" 19 #include "platform/Timer.h"
20 #include "wtf/MainThread.h" 20 #include "wtf/MainThread.h"
21 #include <algorithm> 21 #include <algorithm>
22 22
23 namespace blink { 23 namespace blink {
24 24
25 static void parseRootMargin(String rootMarginParameter, Vector<Length>& rootMarg in, ExceptionState& exceptionState)
26 {
27 // TODO(szager): Make sure this exact syntax and behavior is spec-ed somewhe re.
28
29 // The root margin argument accepts syntax similar to that for CSS margin:
30 //
31 // "1px" = top/right/bottom/left
32 // "1px 2px" = top/bottom left/right
33 // "1px 2px 3px" = top left/right bottom
34 // "1px 2px 3px 4px" = top left right bottom
35 //
36 // Any extra stuff after the first four tokens is ignored.
37 CSSTokenizer::Scope tokenizerScope(rootMarginParameter);
38 CSSParserTokenRange tokenRange = tokenizerScope.tokenRange();
39 while (rootMargin.size() < 4 && tokenRange.peek().type() != EOFToken && !exc eptionState.hadException()) {
40 const CSSParserToken& token = tokenRange.consumeIncludingWhitespace();
41 switch (token.type()) {
42 case PercentageToken:
43 rootMargin.append(Length(token.numericValue(), Percent));
44 break;
45 case DimensionToken:
46 switch (token.unitType()) {
47 case CSSPrimitiveValue::UnitType::Pixels:
48 rootMargin.append(Length(static_cast<int>(floor(token.numericVal ue())), Fixed));
49 break;
50 case CSSPrimitiveValue::UnitType::Percentage:
51 rootMargin.append(Length(token.numericValue(), Percent));
52 break;
53 default:
54 exceptionState.throwTypeError("rootMargin must be specified in p ixels or percent.");
55 }
56 break;
57 default:
58 exceptionState.throwTypeError("rootMargin must be specified in pixel s or percent.");
59 }
60 }
61 }
62
25 static void parseThresholds(const DoubleOrDoubleArray& thresholdParameter, Vecto r<float>& thresholds, ExceptionState& exceptionState) 63 static void parseThresholds(const DoubleOrDoubleArray& thresholdParameter, Vecto r<float>& thresholds, ExceptionState& exceptionState)
26 { 64 {
27 if (thresholdParameter.isDouble()) { 65 if (thresholdParameter.isDouble()) {
28 thresholds.append(static_cast<float>(thresholdParameter.getAsDouble())); 66 thresholds.append(static_cast<float>(thresholdParameter.getAsDouble()));
29 } else { 67 } else {
30 for (auto thresholdValue : thresholdParameter.getAsDoubleArray()) 68 for (auto thresholdValue : thresholdParameter.getAsDoubleArray())
31 thresholds.append(static_cast<float>(thresholdValue)); 69 thresholds.append(static_cast<float>(thresholdValue));
32 } 70 }
33 71
34 for (auto thresholdValue : thresholds) { 72 for (auto thresholdValue : thresholds) {
(...skipping 15 matching lines...) Expand all
50 ASSERT(context->isDocument()); 88 ASSERT(context->isDocument());
51 Frame* mainFrame = toDocument(context)->frame()->tree().top(); 89 Frame* mainFrame = toDocument(context)->frame()->tree().top();
52 if (mainFrame && mainFrame->isLocalFrame()) 90 if (mainFrame && mainFrame->isLocalFrame())
53 root = toLocalFrame(mainFrame)->document()->documentElement(); 91 root = toLocalFrame(mainFrame)->document()->documentElement();
54 } 92 }
55 if (!root) { 93 if (!root) {
56 exceptionState.throwDOMException(HierarchyRequestError, "Unable to get r oot element in main frame to track."); 94 exceptionState.throwDOMException(HierarchyRequestError, "Unable to get r oot element in main frame to track.");
57 return nullptr; 95 return nullptr;
58 } 96 }
59 97
98 Vector<Length> rootMargin;
99 if (observerInit.hasRootMargin())
100 parseRootMargin(observerInit.rootMargin(), rootMargin, exceptionState);
101 if (exceptionState.hadException())
102 return nullptr;
103
60 Vector<float> thresholds; 104 Vector<float> thresholds;
61 if (observerInit.hasThreshold()) 105 if (observerInit.hasThreshold())
62 parseThresholds(observerInit.threshold(), thresholds, exceptionState); 106 parseThresholds(observerInit.threshold(), thresholds, exceptionState);
63 else 107 else
64 thresholds.append(0); 108 thresholds.append(0);
65 if (exceptionState.hadException()) 109 if (exceptionState.hadException())
66 return nullptr; 110 return nullptr;
67 111
68 return new IntersectionObserver(callback, *root, thresholds); 112 return new IntersectionObserver(callback, *root, rootMargin, thresholds);
69 } 113 }
70 114
71 IntersectionObserver::IntersectionObserver(IntersectionObserverCallback& callbac k, Element& root, const Vector<float>& thresholds) 115 IntersectionObserver::IntersectionObserver(IntersectionObserverCallback& callbac k, Element& root, const Vector<Length>& rootMargin, const Vector<float>& thresho lds)
72 : m_callback(&callback) 116 : m_callback(&callback)
73 , m_root(root.ensureIntersectionObserverData().createWeakPtr(&root)) 117 , m_root(root.ensureIntersectionObserverData().createWeakPtr(&root))
74 , m_thresholds(thresholds) 118 , m_thresholds(thresholds)
75 { 119 {
120 switch (rootMargin.size()) {
121 case 0:
122 break;
123 case 1:
124 m_topMargin = m_rightMargin = m_bottomMargin = m_leftMargin = rootMargin [0];
125 break;
126 case 2:
127 m_topMargin = m_bottomMargin = rootMargin[0];
128 m_rightMargin = m_leftMargin = rootMargin[1];
129 break;
130 case 3:
131 m_topMargin = rootMargin[0];
132 m_rightMargin = m_leftMargin = rootMargin[1];
133 m_bottomMargin = rootMargin[2];
134 break;
135 case 4:
136 m_topMargin = rootMargin[0];
137 m_rightMargin = rootMargin[1];
138 m_bottomMargin = rootMargin[2];
139 m_leftMargin = rootMargin[3];
140 break;
141 default:
142 ASSERT_NOT_REACHED();
143 break;
144 }
76 root.document().ensureIntersectionObserverController().addTrackedObserver(*t his); 145 root.document().ensureIntersectionObserverController().addTrackedObserver(*t his);
77 } 146 }
78 147
79 LayoutObject* IntersectionObserver::rootLayoutObject() 148 LayoutObject* IntersectionObserver::rootLayoutObject()
80 { 149 {
81 Element* rootElement = root(); 150 Element* rootElement = root();
82 if (rootElement == rootElement->document().documentElement()) 151 if (rootElement == rootElement->document().documentElement())
83 return rootElement->document().layoutView(); 152 return rootElement->document().layoutView();
84 return rootElement->layoutObject(); 153 return rootElement->layoutObject();
85 } 154 }
(...skipping 31 matching lines...) Expand 10 before | Expand all | Expand 10 after
117 } 186 }
118 if (m_root.get() == target) { 187 if (m_root.get() == target) {
119 exceptionState.throwDOMException(HierarchyRequestError, "Cannot use the same element for root and target."); 188 exceptionState.throwDOMException(HierarchyRequestError, "Cannot use the same element for root and target.");
120 return; 189 return;
121 } 190 }
122 if (!isDescendantOfRoot(target)) { 191 if (!isDescendantOfRoot(target)) {
123 exceptionState.throwDOMException(HierarchyRequestError, "Observed elemen t must be a descendant of the observer's root element."); 192 exceptionState.throwDOMException(HierarchyRequestError, "Observed elemen t must be a descendant of the observer's root element.");
124 return; 193 return;
125 } 194 }
126 195
196 // TODO(szager): Add a pointer to the spec that describes this policy.
127 bool shouldReportRootBounds = target->document().frame()->securityContext()- >securityOrigin()->canAccess(root()->document().frame()->securityContext()->secu rityOrigin()); 197 bool shouldReportRootBounds = target->document().frame()->securityContext()- >securityOrigin()->canAccess(root()->document().frame()->securityContext()->secu rityOrigin());
198 if (!shouldReportRootBounds && hasPercentMargin()) {
199 exceptionState.throwDOMException(HierarchyRequestError, "Cannot observe a cross-origin target because the observer has a root margin value specified as a percent.");
200 return;
201 }
128 202
129 if (target->ensureIntersectionObserverData().getObservationFor(*this)) 203 if (target->ensureIntersectionObserverData().getObservationFor(*this))
130 return; 204 return;
131 205
132 IntersectionObservation* observation = new IntersectionObservation(*this, *t arget, shouldReportRootBounds); 206 IntersectionObservation* observation = new IntersectionObservation(*this, *t arget, shouldReportRootBounds);
133 target->ensureIntersectionObserverData().addObservation(*observation); 207 target->ensureIntersectionObserverData().addObservation(*observation);
134 m_observations.add(observation); 208 m_observations.add(observation);
135 } 209 }
136 210
137 void IntersectionObserver::unobserve(Element* target, ExceptionState&) 211 void IntersectionObserver::unobserve(Element* target, ExceptionState&)
(...skipping 36 matching lines...) Expand 10 before | Expand all | Expand 10 after
174 entries.swap(m_entries); 248 entries.swap(m_entries);
175 return entries; 249 return entries;
176 } 250 }
177 251
178 void IntersectionObserver::enqueueIntersectionObserverEntry(IntersectionObserver Entry& entry) 252 void IntersectionObserver::enqueueIntersectionObserverEntry(IntersectionObserver Entry& entry)
179 { 253 {
180 m_entries.append(&entry); 254 m_entries.append(&entry);
181 toDocument(m_callback->executionContext())->ensureIntersectionObserverContro ller().scheduleIntersectionObserverForDelivery(*this); 255 toDocument(m_callback->executionContext())->ensureIntersectionObserverContro ller().scheduleIntersectionObserverForDelivery(*this);
182 } 256 }
183 257
258 static LayoutUnit computeMargin(const Length& length, LayoutUnit referenceLength )
259 {
260 if (length.type() == Percent)
261 return LayoutUnit(static_cast<int>(referenceLength.toFloat() * length.pe rcent() / 100.0));
262 ASSERT(length.type() == Fixed);
263 return LayoutUnit(length.intValue());
264 }
265
266 void IntersectionObserver::applyRootMargin(LayoutRect& rect) const
267 {
268 // TODO(szager): Make sure the spec is clear that left/right margins are res olved against
269 // width and not height.
270 LayoutUnit topMargin = computeMargin(m_topMargin, rect.height());
271 LayoutUnit rightMargin = computeMargin(m_rightMargin, rect.width());
272 LayoutUnit bottomMargin = computeMargin(m_bottomMargin, rect.height());
273 LayoutUnit leftMargin = computeMargin(m_leftMargin, rect.width());
274
275 rect.setX(rect.x() - leftMargin);
276 rect.setWidth(rect.width() + leftMargin + rightMargin);
277 rect.setY(rect.y() - topMargin);
278 rect.setHeight(rect.height() + topMargin + bottomMargin);
279 }
280
184 unsigned IntersectionObserver::firstThresholdGreaterThan(float ratio) const 281 unsigned IntersectionObserver::firstThresholdGreaterThan(float ratio) const
185 { 282 {
186 unsigned result = 0; 283 unsigned result = 0;
187 while (result < m_thresholds.size() && m_thresholds[result] < ratio) 284 while (result < m_thresholds.size() && m_thresholds[result] < ratio)
188 ++result; 285 ++result;
189 return result; 286 return result;
190 } 287 }
191 288
192 void IntersectionObserver::deliver() 289 void IntersectionObserver::deliver()
193 { 290 {
194 checkRootAndDetachIfNeeded(); 291 checkRootAndDetachIfNeeded();
195 292
196 if (m_entries.isEmpty()) 293 if (m_entries.isEmpty())
197 return; 294 return;
198 295
199 HeapVector<Member<IntersectionObserverEntry>> entries; 296 HeapVector<Member<IntersectionObserverEntry>> entries;
200 entries.swap(m_entries); 297 entries.swap(m_entries);
201 m_callback->handleEvent(entries, *this); 298 m_callback->handleEvent(entries, *this);
202 } 299 }
203 300
204 void IntersectionObserver::setActive(bool active) 301 void IntersectionObserver::setActive(bool active)
205 { 302 {
206 checkRootAndDetachIfNeeded(); 303 checkRootAndDetachIfNeeded();
207 for (auto& observation : m_observations) 304 for (auto& observation : m_observations)
208 observation->setActive(m_root && active && isDescendantOfRoot(observatio n->target())); 305 observation->setActive(m_root && active && isDescendantOfRoot(observatio n->target()));
209 } 306 }
210 307
308 bool IntersectionObserver::hasPercentMargin() const
309 {
310 return (m_topMargin.type() == Percent
311 || m_rightMargin.type() == Percent
312 || m_bottomMargin.type() == Percent
313 || m_leftMargin.type() == Percent);
314 }
315
211 void IntersectionObserver::checkRootAndDetachIfNeeded() 316 void IntersectionObserver::checkRootAndDetachIfNeeded()
212 { 317 {
213 #if ENABLE(OILPAN) 318 #if ENABLE(OILPAN)
214 // TODO(szager): Pre-oilpan, ElementIntersectionObserverData::dispose() will take 319 // TODO(szager): Pre-oilpan, ElementIntersectionObserverData::dispose() will take
215 // care of this cleanup. When oilpan ships, there will be a potential leak of the 320 // care of this cleanup. When oilpan ships, there will be a potential leak of the
216 // callback's execution context when the root goes away. For a detailed exp lanation: 321 // callback's execution context when the root goes away. For a detailed exp lanation:
217 // 322 //
218 // https://goo.gl/PC2Baj 323 // https://goo.gl/PC2Baj
219 // 324 //
220 // When that happens, this method should catch most potential leaks, but a c omplete 325 // When that happens, this method should catch most potential leaks, but a c omplete
221 // solution will still be needed, along the lines described in the above lin k. 326 // solution will still be needed, along the lines described in the above lin k.
222 if (m_root) 327 if (m_root)
223 return; 328 return;
224 disconnect(); 329 disconnect();
225 #endif 330 #endif
226 } 331 }
227 332
228 DEFINE_TRACE(IntersectionObserver) 333 DEFINE_TRACE(IntersectionObserver)
229 { 334 {
230 visitor->trace(m_callback); 335 visitor->trace(m_callback);
231 visitor->trace(m_root); 336 visitor->trace(m_root);
232 visitor->trace(m_observations); 337 visitor->trace(m_observations);
233 visitor->trace(m_entries); 338 visitor->trace(m_entries);
234 } 339 }
235 340
236 } // namespace blink 341 } // namespace blink
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698