2 * Copyright (C) 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
3 * Copyright (C) 2010 Google Inc. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are
9 * * Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * * Redistributions in binary form must reproduce the above
12 * copyright notice, this list of conditions and the following disclaimer
13 * in the documentation and/or other materials provided with the
15 * * Neither the name of Google Inc. nor the names of its
16 * contributors may be used to endorse or promote products derived from
17 * this software without specific prior written permission.
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34 #include "SliderThumbElement.h"
36 #include "CSSValueKeywords.h"
38 #include "EventHandler.h"
39 #include "EventNames.h"
41 #include "HTMLInputElement.h"
42 #include "HTMLParserIdioms.h"
43 #include "MouseEvent.h"
44 #include "RenderFlexibleBox.h"
45 #include "RenderSlider.h"
46 #include "RenderTheme.h"
47 #include "ShadowRoot.h"
48 #include "StyleResolver.h"
50 #if ENABLE(IOS_TOUCH_EVENTS)
53 #include "TouchEvent.h"
58 using namespace HTMLNames;
60 inline static Decimal sliderPosition(HTMLInputElement& element)
62 const StepRange stepRange(element.createStepRange(RejectAny));
63 const Decimal oldValue = parseToDecimalForNumberType(element.value(), stepRange.defaultValue());
64 return stepRange.proportionFromValue(stepRange.clampValue(oldValue));
67 inline static bool hasVerticalAppearance(HTMLInputElement& input)
69 ASSERT(input.renderer());
70 const RenderStyle& sliderStyle = input.renderer()->style();
73 if (sliderStyle.appearance() == MediaVolumeSliderPart && input.renderer()->theme().usesVerticalVolumeSlider())
77 return sliderStyle.appearance() == SliderVerticalPart;
80 // --------------------------------
82 RenderSliderThumb::RenderSliderThumb(SliderThumbElement& element, RenderStyle&& style)
83 : RenderBlockFlow(element, WTFMove(style))
87 void RenderSliderThumb::updateAppearance(const RenderStyle* parentStyle)
89 if (parentStyle->appearance() == SliderVerticalPart)
90 mutableStyle().setAppearance(SliderThumbVerticalPart);
91 else if (parentStyle->appearance() == SliderHorizontalPart)
92 mutableStyle().setAppearance(SliderThumbHorizontalPart);
93 else if (parentStyle->appearance() == MediaSliderPart)
94 mutableStyle().setAppearance(MediaSliderThumbPart);
95 else if (parentStyle->appearance() == MediaVolumeSliderPart)
96 mutableStyle().setAppearance(MediaVolumeSliderThumbPart);
97 else if (parentStyle->appearance() == MediaFullScreenVolumeSliderPart)
98 mutableStyle().setAppearance(MediaFullScreenVolumeSliderThumbPart);
99 if (style().hasAppearance()) {
101 theme().adjustSliderThumbSize(mutableStyle(), element());
105 bool RenderSliderThumb::isSliderThumb() const
110 // --------------------------------
112 // FIXME: Find a way to cascade appearance and adjust heights, and get rid of this class.
113 // http://webkit.org/b/62535
114 class RenderSliderContainer final : public RenderFlexibleBox {
116 RenderSliderContainer(SliderContainerElement& element, RenderStyle&& style)
117 : RenderFlexibleBox(element, WTFMove(style))
122 RenderBox::LogicalExtentComputedValues computeLogicalHeight(LayoutUnit logicalHeight, LayoutUnit logicalTop) const override;
125 void layout() override;
126 bool isFlexibleBoxImpl() const override { return true; }
129 RenderBox::LogicalExtentComputedValues RenderSliderContainer::computeLogicalHeight(LayoutUnit logicalHeight, LayoutUnit logicalTop) const
131 ASSERT(element()->shadowHost());
132 auto& input = downcast<HTMLInputElement>(*element()->shadowHost());
133 bool isVertical = hasVerticalAppearance(input);
135 #if ENABLE(DATALIST_ELEMENT)
136 if (input.renderer()->isSlider() && !isVertical && input.list()) {
137 int offsetFromCenter = theme().sliderTickOffsetFromTrackCenter();
138 LayoutUnit trackHeight = 0;
139 if (offsetFromCenter < 0)
140 trackHeight = -2 * offsetFromCenter;
142 int tickLength = theme().sliderTickSize().height();
143 trackHeight = 2 * (offsetFromCenter + tickLength);
145 float zoomFactor = style().effectiveZoom();
146 if (zoomFactor != 1.0)
147 trackHeight *= zoomFactor;
149 return RenderBox::computeLogicalHeight(trackHeight, logicalTop);
153 logicalHeight = RenderSlider::defaultTrackLength;
154 return RenderBox::computeLogicalHeight(logicalHeight, logicalTop);
157 void RenderSliderContainer::layout()
159 ASSERT(element()->shadowHost());
160 auto& input = downcast<HTMLInputElement>(*element()->shadowHost());
161 bool isVertical = hasVerticalAppearance(input);
162 mutableStyle().setFlexDirection(isVertical ? FlowColumn : FlowRow);
163 TextDirection oldTextDirection = style().direction();
165 // FIXME: Work around rounding issues in RTL vertical sliders. We want them to
166 // render identically to LTR vertical sliders. We can remove this work around when
167 // subpixel rendering is enabled on all ports.
168 mutableStyle().setDirection(LTR);
171 RenderBox* thumb = input.sliderThumbElement() ? input.sliderThumbElement()->renderBox() : nullptr;
172 RenderBox* track = input.sliderTrackElement() ? input.sliderTrackElement()->renderBox() : nullptr;
173 // Force a layout to reset the position of the thumb so the code below doesn't move the thumb to the wrong place.
174 // FIXME: Make a custom Render class for the track and move the thumb positioning code there.
176 track->setChildNeedsLayout(MarkOnlyThis);
178 RenderFlexibleBox::layout();
180 mutableStyle().setDirection(oldTextDirection);
181 // These should always exist, unless someone mutates the shadow DOM (e.g., in the inspector).
182 if (!thumb || !track)
185 double percentageOffset = sliderPosition(input).toDouble();
186 LayoutUnit availableExtent = isVertical ? track->contentHeight() : track->contentWidth();
187 availableExtent -= isVertical ? thumb->height() : thumb->width();
188 LayoutUnit offset = percentageOffset * availableExtent;
189 LayoutPoint thumbLocation = thumb->location();
191 thumbLocation.setY(thumbLocation.y() + track->contentHeight() - thumb->height() - offset);
192 else if (style().isLeftToRightDirection())
193 thumbLocation.setX(thumbLocation.x() + offset);
195 thumbLocation.setX(thumbLocation.x() - offset);
196 thumb->setLocation(thumbLocation);
200 // --------------------------------
202 SliderThumbElement::SliderThumbElement(Document& document)
203 : HTMLDivElement(HTMLNames::divTag, document)
204 , m_inDragMode(false)
205 #if ENABLE(IOS_TOUCH_EVENTS)
206 , m_exclusiveTouchIdentifier(NoIdentifier)
207 , m_isRegisteredAsTouchEventListener(false)
210 setHasCustomStyleResolveCallbacks();
213 void SliderThumbElement::setPositionFromValue()
215 // Since the code to calculate position is in the RenderSliderThumb layout
216 // path, we don't actually update the value here. Instead, we poke at the
217 // renderer directly to trigger layout.
219 renderer()->setNeedsLayout();
222 RenderPtr<RenderElement> SliderThumbElement::createElementRenderer(RenderStyle&& style, const RenderTreePosition&)
224 return createRenderer<RenderSliderThumb>(*this, WTFMove(style));
227 bool SliderThumbElement::isDisabledFormControl() const
229 HTMLInputElement* input = hostInput();
230 return !input || input->isDisabledFormControl();
233 bool SliderThumbElement::matchesReadWritePseudoClass() const
235 HTMLInputElement* input = hostInput();
236 return input && input->matchesReadWritePseudoClass();
239 Element* SliderThumbElement::focusDelegate()
244 void SliderThumbElement::dragFrom(const LayoutPoint& point)
246 Ref<SliderThumbElement> protectedThis(*this);
247 setPositionFromPoint(point);
253 void SliderThumbElement::setPositionFromPoint(const LayoutPoint& absolutePoint)
255 RefPtr<HTMLInputElement> input = hostInput();
259 auto* inputRenderer = input->renderBox();
263 auto* thumbRenderer = renderBox();
267 ASSERT(input->sliderTrackElement());
268 auto* trackRenderer = input->sliderTrackElement()->renderBox();
272 // Do all the tracking math relative to the input's renderer's box.
274 bool isVertical = hasVerticalAppearance(*input);
275 bool isLeftToRightDirection = thumbRenderer->style().isLeftToRightDirection();
277 auto offset = inputRenderer->absoluteToLocal(absolutePoint, UseTransforms);
278 auto trackBoundingBox = trackRenderer->localToContainerQuad(FloatRect { { }, trackRenderer->size() }, inputRenderer).enclosingBoundingBox();
280 LayoutUnit trackLength;
283 trackLength = trackRenderer->contentHeight() - thumbRenderer->height();
284 position = offset.y() - thumbRenderer->height() / 2 - trackBoundingBox.y() - thumbRenderer->marginBottom();
286 trackLength = trackRenderer->contentWidth() - thumbRenderer->width();
287 position = offset.x() - thumbRenderer->width() / 2 - trackBoundingBox.x();
288 position -= isLeftToRightDirection ? thumbRenderer->marginLeft() : thumbRenderer->marginRight();
291 position = std::max<LayoutUnit>(0, std::min(position, trackLength));
292 auto ratio = Decimal::fromDouble(static_cast<double>(position) / trackLength);
293 auto fraction = isVertical || !isLeftToRightDirection ? Decimal(1) - ratio : ratio;
294 auto stepRange = input->createStepRange(RejectAny);
295 auto value = stepRange.clampValue(stepRange.valueFromProportion(fraction));
297 #if ENABLE(DATALIST_ELEMENT)
298 const LayoutUnit snappingThreshold = renderer()->theme().sliderTickSnappingThreshold();
299 if (snappingThreshold > 0) {
300 if (std::optional<Decimal> closest = input->findClosestTickMarkValue(value)) {
301 double closestFraction = stepRange.proportionFromValue(*closest).toDouble();
302 double closestRatio = isVertical || !isLeftToRightDirection ? 1.0 - closestFraction : closestFraction;
303 LayoutUnit closestPosition = trackLength * closestRatio;
304 if ((closestPosition - position).abs() <= snappingThreshold)
310 String valueString = serializeForNumberType(value);
311 if (valueString == input->value())
314 // FIXME: This is no longer being set from renderer. Consider updating the method name.
315 input->setValueFromRenderer(valueString);
317 renderer()->setNeedsLayout();
320 void SliderThumbElement::startDragging()
322 if (Frame* frame = document().frame()) {
323 frame->eventHandler().setCapturingMouseEventsElement(this);
328 void SliderThumbElement::stopDragging()
333 if (Frame* frame = document().frame())
334 frame->eventHandler().setCapturingMouseEventsElement(nullptr);
335 m_inDragMode = false;
337 renderer()->setNeedsLayout();
341 void SliderThumbElement::defaultEventHandler(Event& event)
343 if (!is<MouseEvent>(event)) {
344 HTMLDivElement::defaultEventHandler(event);
348 // FIXME: Should handle this readonly/disabled check in more general way.
349 // Missing this kind of check is likely to occur elsewhere if adding it in each shadow element.
350 HTMLInputElement* input = hostInput();
351 if (!input || input->isDisabledFormControl()) {
353 HTMLDivElement::defaultEventHandler(event);
357 MouseEvent& mouseEvent = downcast<MouseEvent>(event);
358 bool isLeftButton = mouseEvent.button() == LeftButton;
359 const AtomicString& eventType = mouseEvent.type();
361 // We intentionally do not call event->setDefaultHandled() here because
362 // MediaControlTimelineElement::defaultEventHandler() wants to handle these
364 if (eventType == eventNames().mousedownEvent && isLeftButton) {
367 } else if (eventType == eventNames().mouseupEvent && isLeftButton) {
368 input->dispatchFormControlChangeEvent();
371 } else if (eventType == eventNames().mousemoveEvent) {
373 setPositionFromPoint(mouseEvent.absoluteLocation());
377 HTMLDivElement::defaultEventHandler(mouseEvent);
382 bool SliderThumbElement::willRespondToMouseMoveEvents()
384 const HTMLInputElement* input = hostInput();
385 if (input && !input->isDisabledFormControl() && m_inDragMode)
388 return HTMLDivElement::willRespondToMouseMoveEvents();
391 bool SliderThumbElement::willRespondToMouseClickEvents()
393 const HTMLInputElement* input = hostInput();
394 if (input && !input->isDisabledFormControl())
397 return HTMLDivElement::willRespondToMouseClickEvents();
399 #endif // !PLATFORM(IOS)
401 void SliderThumbElement::willDetachRenderers()
404 if (Frame* frame = document().frame())
405 frame->eventHandler().setCapturingMouseEventsElement(nullptr);
407 #if ENABLE(IOS_TOUCH_EVENTS)
408 unregisterForTouchEvents();
412 #if ENABLE(IOS_TOUCH_EVENTS)
413 unsigned SliderThumbElement::exclusiveTouchIdentifier() const
415 return m_exclusiveTouchIdentifier;
418 void SliderThumbElement::setExclusiveTouchIdentifier(unsigned identifier)
420 ASSERT(m_exclusiveTouchIdentifier == NoIdentifier);
421 m_exclusiveTouchIdentifier = identifier;
424 void SliderThumbElement::clearExclusiveTouchIdentifier()
426 m_exclusiveTouchIdentifier = NoIdentifier;
429 static Touch* findTouchWithIdentifier(TouchList& list, unsigned identifier)
431 unsigned length = list.length();
432 for (unsigned i = 0; i < length; ++i) {
433 Touch* touch = list.item(i);
434 if (touch->identifier() == identifier)
440 void SliderThumbElement::handleTouchStart(TouchEvent& touchEvent)
442 TouchList* targetTouches = touchEvent.targetTouches();
446 if (targetTouches->length() != 1)
449 Touch* touch = targetTouches->item(0);
452 IntRect boundingBox = renderer()->absoluteBoundingBoxRect();
453 // Ignore the touch if it is not really inside the thumb.
454 if (!boundingBox.contains(touch->pageX(), touch->pageY()))
457 setExclusiveTouchIdentifier(touch->identifier());
460 touchEvent.setDefaultHandled();
463 void SliderThumbElement::handleTouchMove(TouchEvent& touchEvent)
465 unsigned identifier = exclusiveTouchIdentifier();
466 if (identifier == NoIdentifier)
469 TouchList* targetTouches = touchEvent.targetTouches();
473 Touch* touch = findTouchWithIdentifier(*targetTouches, identifier);
478 setPositionFromPoint(IntPoint(touch->pageX(), touch->pageY()));
479 touchEvent.setDefaultHandled();
482 void SliderThumbElement::handleTouchEndAndCancel(TouchEvent& touchEvent)
484 unsigned identifier = exclusiveTouchIdentifier();
485 if (identifier == NoIdentifier)
488 TouchList* targetTouches = touchEvent.targetTouches();
491 // If our exclusive touch still exists, it was not the touch
492 // that ended, so we should not stop dragging.
493 Touch* exclusiveTouch = findTouchWithIdentifier(*targetTouches, identifier);
497 clearExclusiveTouchIdentifier();
499 RefPtr<HTMLInputElement> input = hostInput();
501 input->dispatchFormControlChangeEvent();
505 void SliderThumbElement::didAttachRenderers()
507 if (shouldAcceptTouchEvents())
508 registerForTouchEvents();
511 void SliderThumbElement::handleTouchEvent(TouchEvent& touchEvent)
513 HTMLInputElement* input = hostInput();
515 if (input->isReadOnly() || input->isDisabledFormControl()) {
516 clearExclusiveTouchIdentifier();
518 touchEvent.setDefaultHandled();
519 HTMLDivElement::defaultEventHandler(touchEvent);
523 const AtomicString& eventType = touchEvent.type();
524 if (eventType == eventNames().touchstartEvent) {
525 handleTouchStart(touchEvent);
528 if (eventType == eventNames().touchendEvent || eventType == eventNames().touchcancelEvent) {
529 handleTouchEndAndCancel(touchEvent);
532 if (eventType == eventNames().touchmoveEvent) {
533 handleTouchMove(touchEvent);
537 HTMLDivElement::defaultEventHandler(touchEvent);
540 bool SliderThumbElement::shouldAcceptTouchEvents()
542 return renderer() && !isDisabledFormControl();
545 void SliderThumbElement::registerForTouchEvents()
547 if (m_isRegisteredAsTouchEventListener)
550 ASSERT(shouldAcceptTouchEvents());
552 document().addTouchEventHandler(*this);
553 m_isRegisteredAsTouchEventListener = true;
556 void SliderThumbElement::unregisterForTouchEvents()
558 if (!m_isRegisteredAsTouchEventListener)
561 clearExclusiveTouchIdentifier();
564 document().removeTouchEventHandler(*this);
565 m_isRegisteredAsTouchEventListener = false;
568 void SliderThumbElement::disabledAttributeChanged()
570 if (shouldAcceptTouchEvents())
571 registerForTouchEvents();
573 unregisterForTouchEvents();
575 #endif // ENABLE(IOS_TOUCH_EVENTS)
577 HTMLInputElement* SliderThumbElement::hostInput() const
579 // Only HTMLInputElement creates SliderThumbElement instances as its shadow nodes.
580 // So, shadowHost() must be an HTMLInputElement.
581 return downcast<HTMLInputElement>(shadowHost());
584 std::optional<ElementStyle> SliderThumbElement::resolveCustomStyle(const RenderStyle&, const RenderStyle* hostStyle)
586 // This doesn't actually compute style. This is just a hack to pick shadow pseudo id when host style is known.
588 static NeverDestroyed<const AtomicString> sliderThumbShadowPseudoId("-webkit-slider-thumb", AtomicString::ConstructFromLiteral);
589 static NeverDestroyed<const AtomicString> mediaSliderThumbShadowPseudoId("-webkit-media-slider-thumb", AtomicString::ConstructFromLiteral);
594 switch (hostStyle->appearance()) {
595 case MediaSliderPart:
596 case MediaSliderThumbPart:
597 case MediaVolumeSliderPart:
598 case MediaVolumeSliderThumbPart:
599 case MediaFullScreenVolumeSliderPart:
600 case MediaFullScreenVolumeSliderThumbPart:
601 m_shadowPseudoId = mediaSliderThumbShadowPseudoId;
604 m_shadowPseudoId = sliderThumbShadowPseudoId;
610 const AtomicString& SliderThumbElement::shadowPseudoId() const
612 return m_shadowPseudoId;
615 Ref<Element> SliderThumbElement::cloneElementWithoutAttributesAndChildren(Document& targetDocument)
617 return create(targetDocument);
620 // --------------------------------
622 inline SliderContainerElement::SliderContainerElement(Document& document)
623 : HTMLDivElement(HTMLNames::divTag, document)
625 setHasCustomStyleResolveCallbacks();
628 Ref<SliderContainerElement> SliderContainerElement::create(Document& document)
630 return adoptRef(*new SliderContainerElement(document));
633 RenderPtr<RenderElement> SliderContainerElement::createElementRenderer(RenderStyle&& style, const RenderTreePosition&)
635 return createRenderer<RenderSliderContainer>(*this, WTFMove(style));
638 std::optional<ElementStyle> SliderContainerElement::resolveCustomStyle(const RenderStyle&, const RenderStyle* hostStyle)
640 // This doesn't actually compute style. This is just a hack to pick shadow pseudo id when host style is known.
642 static NeverDestroyed<const AtomicString> mediaSliderContainer("-webkit-media-slider-container", AtomicString::ConstructFromLiteral);
643 static NeverDestroyed<const AtomicString> sliderContainer("-webkit-slider-container", AtomicString::ConstructFromLiteral);
648 switch (hostStyle->appearance()) {
649 case MediaSliderPart:
650 case MediaSliderThumbPart:
651 case MediaVolumeSliderPart:
652 case MediaVolumeSliderThumbPart:
653 case MediaFullScreenVolumeSliderPart:
654 case MediaFullScreenVolumeSliderThumbPart:
655 m_shadowPseudoId = mediaSliderContainer;
658 m_shadowPseudoId = sliderContainer;
664 const AtomicString& SliderContainerElement::shadowPseudoId() const
666 return m_shadowPseudoId;