1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382
|
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "core/dom/IntersectionObserver.h"
#include "bindings/core/v8/ExceptionState.h"
#include "core/css/parser/CSSParserTokenRange.h"
#include "core/css/parser/CSSTokenizer.h"
#include "core/dom/Element.h"
#include "core/dom/ElementIntersectionObserverData.h"
#include "core/dom/ExceptionCode.h"
#include "core/dom/ExecutionContext.h"
#include "core/dom/IntersectionObserverCallback.h"
#include "core/dom/IntersectionObserverController.h"
#include "core/dom/IntersectionObserverEntry.h"
#include "core/dom/IntersectionObserverInit.h"
#include "core/frame/FrameView.h"
#include "core/frame/LocalDOMWindow.h"
#include "core/frame/LocalFrame.h"
#include "core/inspector/ConsoleMessage.h"
#include "core/layout/LayoutView.h"
#include "core/timing/DOMWindowPerformance.h"
#include "core/timing/Performance.h"
#include "platform/Timer.h"
#include <algorithm>
namespace blink {
namespace {
// Internal implementation of IntersectionObserverCallback when using
// IntersectionObserver with an EventCallback.
class IntersectionObserverCallbackImpl final
: public IntersectionObserverCallback {
WTF_MAKE_NONCOPYABLE(IntersectionObserverCallbackImpl);
public:
IntersectionObserverCallbackImpl(
ExecutionContext* context,
std::unique_ptr<IntersectionObserver::EventCallback> callback)
: m_context(context), m_callback(std::move(callback)) {}
void handleEvent(const HeapVector<Member<IntersectionObserverEntry>>& entries,
IntersectionObserver&) override {
(*m_callback.get())(entries);
}
ExecutionContext* getExecutionContext() const override { return m_context; }
DEFINE_INLINE_TRACE() {
IntersectionObserverCallback::trace(visitor);
visitor->trace(m_context);
}
private:
WeakMember<ExecutionContext> m_context;
std::unique_ptr<IntersectionObserver::EventCallback> m_callback;
};
void parseRootMargin(String rootMarginParameter,
Vector<Length>& rootMargin,
ExceptionState& exceptionState) {
// TODO(szager): Make sure this exact syntax and behavior is spec-ed
// somewhere.
// The root margin argument accepts syntax similar to that for CSS margin:
//
// "1px" = top/right/bottom/left
// "1px 2px" = top/bottom left/right
// "1px 2px 3px" = top left/right bottom
// "1px 2px 3px 4px" = top left right bottom
CSSTokenizer tokenizer(rootMarginParameter);
CSSParserTokenRange tokenRange = tokenizer.tokenRange();
while (tokenRange.peek().type() != EOFToken &&
!exceptionState.hadException()) {
if (rootMargin.size() == 4) {
exceptionState.throwDOMException(
SyntaxError, "Extra text found at the end of rootMargin.");
break;
}
const CSSParserToken& token = tokenRange.consumeIncludingWhitespace();
switch (token.type()) {
case PercentageToken:
rootMargin.push_back(Length(token.numericValue(), Percent));
break;
case DimensionToken:
switch (token.unitType()) {
case CSSPrimitiveValue::UnitType::Pixels:
rootMargin.push_back(
Length(static_cast<int>(floor(token.numericValue())), Fixed));
break;
case CSSPrimitiveValue::UnitType::Percentage:
rootMargin.push_back(Length(token.numericValue(), Percent));
break;
default:
exceptionState.throwDOMException(
SyntaxError,
"rootMargin must be specified in pixels or percent.");
}
break;
default:
exceptionState.throwDOMException(
SyntaxError, "rootMargin must be specified in pixels or percent.");
}
}
}
void parseThresholds(const DoubleOrDoubleSequence& thresholdParameter,
Vector<float>& thresholds,
ExceptionState& exceptionState) {
if (thresholdParameter.isDouble()) {
thresholds.push_back(static_cast<float>(thresholdParameter.getAsDouble()));
} else {
for (auto thresholdValue : thresholdParameter.getAsDoubleSequence())
thresholds.push_back(static_cast<float>(thresholdValue));
}
for (auto thresholdValue : thresholds) {
if (std::isnan(thresholdValue) || thresholdValue < 0.0 ||
thresholdValue > 1.0) {
exceptionState.throwRangeError(
"Threshold values must be numbers between 0 and 1");
break;
}
}
std::sort(thresholds.begin(), thresholds.end());
}
} // anonymous namespace
IntersectionObserver* IntersectionObserver::create(
const IntersectionObserverInit& observerInit,
IntersectionObserverCallback& callback,
ExceptionState& exceptionState) {
Element* root = observerInit.root();
Vector<Length> rootMargin;
parseRootMargin(observerInit.rootMargin(), rootMargin, exceptionState);
if (exceptionState.hadException())
return nullptr;
Vector<float> thresholds;
parseThresholds(observerInit.threshold(), thresholds, exceptionState);
if (exceptionState.hadException())
return nullptr;
return new IntersectionObserver(callback, root, rootMargin, thresholds);
}
IntersectionObserver* IntersectionObserver::create(
const Vector<Length>& rootMargin,
const Vector<float>& thresholds,
Document* document,
std::unique_ptr<EventCallback> callback,
ExceptionState& exceptionState) {
IntersectionObserverCallbackImpl* intersectionObserverCallback =
new IntersectionObserverCallbackImpl(document, std::move(callback));
return new IntersectionObserver(*intersectionObserverCallback, nullptr,
rootMargin, thresholds);
}
IntersectionObserver::IntersectionObserver(
IntersectionObserverCallback& callback,
Element* root,
const Vector<Length>& rootMargin,
const Vector<float>& thresholds)
: m_callback(&callback),
m_root(root),
m_thresholds(thresholds),
m_topMargin(Fixed),
m_rightMargin(Fixed),
m_bottomMargin(Fixed),
m_leftMargin(Fixed),
m_rootIsImplicit(root ? 0 : 1),
m_initialState(InitialState::kHidden) {
switch (rootMargin.size()) {
case 0:
break;
case 1:
m_topMargin = m_rightMargin = m_bottomMargin = m_leftMargin =
rootMargin[0];
break;
case 2:
m_topMargin = m_bottomMargin = rootMargin[0];
m_rightMargin = m_leftMargin = rootMargin[1];
break;
case 3:
m_topMargin = rootMargin[0];
m_rightMargin = m_leftMargin = rootMargin[1];
m_bottomMargin = rootMargin[2];
break;
case 4:
m_topMargin = rootMargin[0];
m_rightMargin = rootMargin[1];
m_bottomMargin = rootMargin[2];
m_leftMargin = rootMargin[3];
break;
default:
NOTREACHED();
break;
}
if (root)
root->ensureIntersectionObserverData().addObserver(*this);
trackingDocument().ensureIntersectionObserverController().addTrackedObserver(
*this);
}
void IntersectionObserver::clearWeakMembers(Visitor* visitor) {
if (ThreadHeap::isHeapObjectAlive(root()))
return;
DummyExceptionStateForTesting exceptionState;
disconnect(exceptionState);
m_root = nullptr;
}
bool IntersectionObserver::rootIsValid() const {
return rootIsImplicit() || root();
}
Document& IntersectionObserver::trackingDocument() const {
if (rootIsImplicit()) {
DCHECK(m_callback->getExecutionContext());
return *toDocument(m_callback->getExecutionContext());
}
DCHECK(root());
return root()->document();
}
void IntersectionObserver::observe(Element* target,
ExceptionState& exceptionState) {
if (!rootIsValid())
return;
if (!target || root() == target)
return;
LocalFrame* targetFrame = target->document().frame();
if (!targetFrame)
return;
if (target->ensureIntersectionObserverData().getObservationFor(*this))
return;
bool isDOMDescendant = true;
bool shouldReportRootBounds = false;
if (rootIsImplicit()) {
Frame* rootFrame = targetFrame->tree().top();
DCHECK(rootFrame);
if (rootFrame == targetFrame) {
shouldReportRootBounds = true;
} else {
shouldReportRootBounds =
targetFrame->securityContext()->getSecurityOrigin()->canAccess(
rootFrame->securityContext()->getSecurityOrigin());
}
} else {
shouldReportRootBounds = true;
isDOMDescendant = root()->isShadowIncludingInclusiveAncestorOf(target);
}
IntersectionObservation* observation =
new IntersectionObservation(*this, *target, shouldReportRootBounds);
target->ensureIntersectionObserverData().addObservation(*observation);
m_observations.add(observation);
if (!isDOMDescendant) {
root()->document().addConsoleMessage(
ConsoleMessage::create(JSMessageSource, WarningMessageLevel,
"IntersectionObserver.observe(target): target "
"element is not a descendant of root."));
}
if (m_initialState == InitialState::kAuto) {
for (auto& observation : m_observations)
observation->setLastThresholdIndex(std::numeric_limits<unsigned>::max());
}
if (FrameView* frameView = targetFrame->view())
frameView->scheduleAnimation();
}
void IntersectionObserver::unobserve(Element* target,
ExceptionState& exceptionState) {
if (!target || !target->intersectionObserverData())
return;
if (IntersectionObservation* observation =
target->intersectionObserverData()->getObservationFor(*this)) {
observation->disconnect();
m_observations.remove(observation);
}
}
void IntersectionObserver::computeIntersectionObservations() {
if (!rootIsValid())
return;
Document* callbackDocument = toDocument(m_callback->getExecutionContext());
if (!callbackDocument)
return;
LocalDOMWindow* callbackDOMWindow = callbackDocument->domWindow();
if (!callbackDOMWindow)
return;
DOMHighResTimeStamp timestamp =
DOMWindowPerformance::performance(*callbackDOMWindow)->now();
for (auto& observation : m_observations)
observation->computeIntersectionObservations(timestamp);
}
void IntersectionObserver::disconnect(ExceptionState& exceptionState) {
for (auto& observation : m_observations)
observation->disconnect();
m_observations.clear();
m_entries.clear();
}
void IntersectionObserver::setInitialState(InitialState initialState) {
DCHECK(m_observations.isEmpty());
m_initialState = initialState;
}
HeapVector<Member<IntersectionObserverEntry>> IntersectionObserver::takeRecords(
ExceptionState& exceptionState) {
HeapVector<Member<IntersectionObserverEntry>> entries;
entries.swap(m_entries);
return entries;
}
static void appendLength(StringBuilder& stringBuilder, const Length& length) {
stringBuilder.appendNumber(length.intValue());
if (length.type() == Percent)
stringBuilder.append('%');
else
stringBuilder.append("px", 2);
}
String IntersectionObserver::rootMargin() const {
StringBuilder stringBuilder;
appendLength(stringBuilder, m_topMargin);
stringBuilder.append(' ');
appendLength(stringBuilder, m_rightMargin);
stringBuilder.append(' ');
appendLength(stringBuilder, m_bottomMargin);
stringBuilder.append(' ');
appendLength(stringBuilder, m_leftMargin);
return stringBuilder.toString();
}
void IntersectionObserver::enqueueIntersectionObserverEntry(
IntersectionObserverEntry& entry) {
m_entries.push_back(&entry);
toDocument(m_callback->getExecutionContext())
->ensureIntersectionObserverController()
.scheduleIntersectionObserverForDelivery(*this);
}
unsigned IntersectionObserver::firstThresholdGreaterThan(float ratio) const {
unsigned result = 0;
while (result < m_thresholds.size() && m_thresholds[result] <= ratio)
++result;
return result;
}
void IntersectionObserver::deliver() {
if (m_entries.isEmpty())
return;
HeapVector<Member<IntersectionObserverEntry>> entries;
entries.swap(m_entries);
m_callback->handleEvent(entries, *this);
}
DEFINE_TRACE(IntersectionObserver) {
visitor->template registerWeakMembers<
IntersectionObserver, &IntersectionObserver::clearWeakMembers>(this);
visitor->trace(m_callback);
visitor->trace(m_observations);
visitor->trace(m_entries);
}
} // namespace blink
|