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()) {
352 HTMLDivElement::defaultEventHandler(event);
356 MouseEvent& mouseEvent = downcast<MouseEvent>(event);
357 bool isLeftButton = mouseEvent.button() == LeftButton;
358 const AtomicString& eventType = mouseEvent.type();
360 // We intentionally do not call event->setDefaultHandled() here because
361 // MediaControlTimelineElement::defaultEventHandler() wants to handle these
363 if (eventType == eventNames().mousedownEvent && isLeftButton) {
366 } else if (eventType == eventNames().mouseupEvent && isLeftButton) {
367 input->dispatchFormControlChangeEvent();
370 } else if (eventType == eventNames().mousemoveEvent) {
372 setPositionFromPoint(mouseEvent.absoluteLocation());
376 HTMLDivElement::defaultEventHandler(mouseEvent);
381 bool SliderThumbElement::willRespondToMouseMoveEvents()
383 const HTMLInputElement* input = hostInput();
384 if (input && !input->isDisabledFormControl() && m_inDragMode)
387 return HTMLDivElement::willRespondToMouseMoveEvents();
390 bool SliderThumbElement::willRespondToMouseClickEvents()
392 const HTMLInputElement* input = hostInput();
393 if (input && !input->isDisabledFormControl())
396 return HTMLDivElement::willRespondToMouseClickEvents();
398 #endif // !PLATFORM(IOS)
400 void SliderThumbElement::willDetachRenderers()
403 if (Frame* frame = document().frame())
404 frame->eventHandler().setCapturingMouseEventsElement(nullptr);
406 #if ENABLE(IOS_TOUCH_EVENTS)
407 unregisterForTouchEvents();
411 #if ENABLE(IOS_TOUCH_EVENTS)
412 unsigned SliderThumbElement::exclusiveTouchIdentifier() const
414 return m_exclusiveTouchIdentifier;
417 void SliderThumbElement::setExclusiveTouchIdentifier(unsigned identifier)
419 ASSERT(m_exclusiveTouchIdentifier == NoIdentifier);
420 m_exclusiveTouchIdentifier = identifier;
423 void SliderThumbElement::clearExclusiveTouchIdentifier()
425 m_exclusiveTouchIdentifier = NoIdentifier;
428 static Touch* findTouchWithIdentifier(TouchList& list, unsigned identifier)
430 unsigned length = list.length();
431 for (unsigned i = 0; i < length; ++i) {
432 Touch* touch = list.item(i);
433 if (touch->identifier() == identifier)
439 void SliderThumbElement::handleTouchStart(TouchEvent& touchEvent)
441 TouchList* targetTouches = touchEvent.targetTouches();
445 if (targetTouches->length() != 1)
448 Touch* touch = targetTouches->item(0);
451 IntRect boundingBox = renderer()->absoluteBoundingBoxRect();
452 // Ignore the touch if it is not really inside the thumb.
453 if (!boundingBox.contains(touch->pageX(), touch->pageY()))
456 setExclusiveTouchIdentifier(touch->identifier());
459 touchEvent.setDefaultHandled();
462 void SliderThumbElement::handleTouchMove(TouchEvent& touchEvent)
464 unsigned identifier = exclusiveTouchIdentifier();
465 if (identifier == NoIdentifier)
468 TouchList* targetTouches = touchEvent.targetTouches();
472 Touch* touch = findTouchWithIdentifier(*targetTouches, identifier);
477 setPositionFromPoint(IntPoint(touch->pageX(), touch->pageY()));
478 touchEvent.setDefaultHandled();
481 void SliderThumbElement::handleTouchEndAndCancel(TouchEvent& touchEvent)
483 unsigned identifier = exclusiveTouchIdentifier();
484 if (identifier == NoIdentifier)
487 TouchList* targetTouches = touchEvent.targetTouches();
490 // If our exclusive touch still exists, it was not the touch
491 // that ended, so we should not stop dragging.
492 Touch* exclusiveTouch = findTouchWithIdentifier(*targetTouches, identifier);
496 clearExclusiveTouchIdentifier();
498 RefPtr<HTMLInputElement> input = hostInput();
500 input->dispatchFormControlChangeEvent();
504 void SliderThumbElement::didAttachRenderers()
506 if (shouldAcceptTouchEvents())
507 registerForTouchEvents();
510 void SliderThumbElement::handleTouchEvent(TouchEvent& touchEvent)
512 HTMLInputElement* input = hostInput();
514 if (input->isReadOnly() || input->isDisabledFormControl()) {
515 clearExclusiveTouchIdentifier();
517 touchEvent.setDefaultHandled();
518 HTMLDivElement::defaultEventHandler(touchEvent);
522 const AtomicString& eventType = touchEvent.type();
523 if (eventType == eventNames().touchstartEvent) {
524 handleTouchStart(touchEvent);
527 if (eventType == eventNames().touchendEvent || eventType == eventNames().touchcancelEvent) {
528 handleTouchEndAndCancel(touchEvent);
531 if (eventType == eventNames().touchmoveEvent) {
532 handleTouchMove(touchEvent);
536 HTMLDivElement::defaultEventHandler(touchEvent);
539 bool SliderThumbElement::shouldAcceptTouchEvents()
541 return renderer() && !isDisabledFormControl();
544 void SliderThumbElement::registerForTouchEvents()
546 if (m_isRegisteredAsTouchEventListener)
549 ASSERT(shouldAcceptTouchEvents());
551 document().addTouchEventHandler(*this);
552 m_isRegisteredAsTouchEventListener = true;
555 void SliderThumbElement::unregisterForTouchEvents()
557 if (!m_isRegisteredAsTouchEventListener)
560 clearExclusiveTouchIdentifier();
563 document().removeTouchEventHandler(*this);
564 m_isRegisteredAsTouchEventListener = false;
566 #endif // ENABLE(IOS_TOUCH_EVENTS)
568 void SliderThumbElement::disabledAttributeChanged()
570 if (isDisabledFormControl())
573 #if ENABLE(IOS_TOUCH_EVENTS)
574 if (shouldAcceptTouchEvents())
575 registerForTouchEvents();
577 unregisterForTouchEvents();
581 HTMLInputElement* SliderThumbElement::hostInput() const
583 // Only HTMLInputElement creates SliderThumbElement instances as its shadow nodes.
584 // So, shadowHost() must be an HTMLInputElement.
585 return downcast<HTMLInputElement>(shadowHost());
588 std::optional<ElementStyle> SliderThumbElement::resolveCustomStyle(const RenderStyle&, const RenderStyle* hostStyle)
590 // This doesn't actually compute style. This is just a hack to pick shadow pseudo id when host style is known.
592 static NeverDestroyed<const AtomicString> sliderThumbShadowPseudoId("-webkit-slider-thumb", AtomicString::ConstructFromLiteral);
593 static NeverDestroyed<const AtomicString> mediaSliderThumbShadowPseudoId("-webkit-media-slider-thumb", AtomicString::ConstructFromLiteral);
598 switch (hostStyle->appearance()) {
599 case MediaSliderPart:
600 case MediaSliderThumbPart:
601 case MediaVolumeSliderPart:
602 case MediaVolumeSliderThumbPart:
603 case MediaFullScreenVolumeSliderPart:
604 case MediaFullScreenVolumeSliderThumbPart:
605 m_shadowPseudoId = mediaSliderThumbShadowPseudoId;
608 m_shadowPseudoId = sliderThumbShadowPseudoId;
614 const AtomicString& SliderThumbElement::shadowPseudoId() const
616 return m_shadowPseudoId;
619 Ref<Element> SliderThumbElement::cloneElementWithoutAttributesAndChildren(Document& targetDocument)
621 return create(targetDocument);
624 // --------------------------------
626 inline SliderContainerElement::SliderContainerElement(Document& document)
627 : HTMLDivElement(HTMLNames::divTag, document)
629 setHasCustomStyleResolveCallbacks();
632 Ref<SliderContainerElement> SliderContainerElement::create(Document& document)
634 return adoptRef(*new SliderContainerElement(document));
637 RenderPtr<RenderElement> SliderContainerElement::createElementRenderer(RenderStyle&& style, const RenderTreePosition&)
639 return createRenderer<RenderSliderContainer>(*this, WTFMove(style));
642 std::optional<ElementStyle> SliderContainerElement::resolveCustomStyle(const RenderStyle&, const RenderStyle* hostStyle)
644 // This doesn't actually compute style. This is just a hack to pick shadow pseudo id when host style is known.
646 static NeverDestroyed<const AtomicString> mediaSliderContainer("-webkit-media-slider-container", AtomicString::ConstructFromLiteral);
647 static NeverDestroyed<const AtomicString> sliderContainer("-webkit-slider-container", AtomicString::ConstructFromLiteral);
652 switch (hostStyle->appearance()) {
653 case MediaSliderPart:
654 case MediaSliderThumbPart:
655 case MediaVolumeSliderPart:
656 case MediaVolumeSliderThumbPart:
657 case MediaFullScreenVolumeSliderPart:
658 case MediaFullScreenVolumeSliderThumbPart:
659 m_shadowPseudoId = mediaSliderContainer;
662 m_shadowPseudoId = sliderContainer;
668 const AtomicString& SliderContainerElement::shadowPseudoId() const
670 return m_shadowPseudoId;