2 * Copyright (C) 2010 Google Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions are
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above
11 * copyright notice, this list of conditions and the following disclaimer
12 * in the documentation and/or other materials provided with the
14 * * Neither the name of Google Inc. nor the names of its
15 * contributors may be used to endorse or promote products derived from
16 * this software without specific prior written permission.
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 #if ENABLE(INPUT_MULTIPLE_FIELDS_UI)
33 #include "core/html/forms/BaseMultipleFieldsDateAndTimeInputType.h"
35 #include "core/CSSValueKeywords.h"
36 #include "core/dom/shadow/ShadowRoot.h"
37 #include "core/events/KeyboardEvent.h"
38 #include "core/events/ScopedEventQueue.h"
39 #include "core/html/HTMLDataListElement.h"
40 #include "core/html/HTMLInputElement.h"
41 #include "core/html/HTMLOptionElement.h"
42 #include "core/html/forms/DateTimeFieldsState.h"
43 #include "core/html/forms/FormController.h"
44 #include "core/html/shadow/ShadowElementNames.h"
45 #include "core/page/FocusController.h"
46 #include "core/page/Page.h"
47 #include "core/rendering/RenderTheme.h"
48 #include "platform/DateComponents.h"
49 #include "platform/RuntimeEnabledFeatures.h"
50 #include "platform/text/DateTimeFormat.h"
51 #include "platform/text/PlatformLocale.h"
52 #include "wtf/DateMath.h"
56 class DateTimeFormatValidator : public DateTimeFormat::TokenHandler {
58 DateTimeFormatValidator()
66 , m_hasSecond(false) { }
68 virtual void visitField(DateTimeFormat::FieldType, int) OVERRIDE FINAL;
69 virtual void visitLiteral(const String&) OVERRIDE FINAL { }
71 bool validateFormat(const String& format, const BaseMultipleFieldsDateAndTimeInputType&);
84 void DateTimeFormatValidator::visitField(DateTimeFormat::FieldType fieldType, int)
87 case DateTimeFormat::FieldTypeYear:
90 case DateTimeFormat::FieldTypeMonth: // Fallthrough.
91 case DateTimeFormat::FieldTypeMonthStandAlone:
94 case DateTimeFormat::FieldTypeWeekOfYear:
97 case DateTimeFormat::FieldTypeDayOfMonth:
100 case DateTimeFormat::FieldTypePeriod:
103 case DateTimeFormat::FieldTypeHour11: // Fallthrough.
104 case DateTimeFormat::FieldTypeHour12:
107 case DateTimeFormat::FieldTypeHour23: // Fallthrough.
108 case DateTimeFormat::FieldTypeHour24:
112 case DateTimeFormat::FieldTypeMinute:
115 case DateTimeFormat::FieldTypeSecond:
123 bool DateTimeFormatValidator::validateFormat(const String& format, const BaseMultipleFieldsDateAndTimeInputType& inputType)
125 if (!DateTimeFormat::parse(format, *this))
127 return inputType.isValidFormat(m_hasYear, m_hasMonth, m_hasWeek, m_hasDay, m_hasAMPM, m_hasHour, m_hasMinute, m_hasSecond);
130 DateTimeEditElement* BaseMultipleFieldsDateAndTimeInputType::dateTimeEditElement() const
132 return toDateTimeEditElement(element().userAgentShadowRoot()->getElementById(ShadowElementNames::dateTimeEdit()));
135 SpinButtonElement* BaseMultipleFieldsDateAndTimeInputType::spinButtonElement() const
137 return toSpinButtonElement(element().userAgentShadowRoot()->getElementById(ShadowElementNames::spinButton()));
140 ClearButtonElement* BaseMultipleFieldsDateAndTimeInputType::clearButtonElement() const
142 return toClearButtonElement(element().userAgentShadowRoot()->getElementById(ShadowElementNames::clearButton()));
145 PickerIndicatorElement* BaseMultipleFieldsDateAndTimeInputType::pickerIndicatorElement() const
147 return toPickerIndicatorElement(element().userAgentShadowRoot()->getElementById(ShadowElementNames::pickerIndicator()));
150 inline bool BaseMultipleFieldsDateAndTimeInputType::containsFocusedShadowElement() const
152 return element().userAgentShadowRoot()->contains(element().document().focusedElement());
155 void BaseMultipleFieldsDateAndTimeInputType::didBlurFromControl()
157 // We don't need to call blur(). This function is called when control
160 if (containsFocusedShadowElement())
162 EventQueueScope scope;
163 RefPtrWillBeRawPtr<HTMLInputElement> protector(element());
164 // Remove focus ring by CSS "focus" pseudo class.
165 element().setFocus(false);
166 if (SpinButtonElement *spinButton = spinButtonElement())
167 spinButton->releaseCapture();
170 void BaseMultipleFieldsDateAndTimeInputType::didFocusOnControl()
172 // We don't need to call focus(). This function is called when control
175 if (!containsFocusedShadowElement())
177 // Add focus ring by CSS "focus" pseudo class.
178 // FIXME: Setting the focus flag to non-focused element is too tricky.
179 element().setFocus(true);
182 void BaseMultipleFieldsDateAndTimeInputType::editControlValueChanged()
184 RefPtrWillBeRawPtr<HTMLInputElement> input(element());
185 String oldValue = input->value();
186 String newValue = sanitizeValue(dateTimeEditElement()->value());
187 // Even if oldValue is null and newValue is "", we should assume they are same.
188 if ((oldValue.isEmpty() && newValue.isEmpty()) || oldValue == newValue) {
189 input->setNeedsValidityCheck();
191 input->setValueInternal(newValue, DispatchNoEvent);
192 input->setNeedsStyleRecalc(SubtreeStyleChange);
193 input->dispatchFormControlInputEvent();
195 input->notifyFormStateChanged();
196 input->updateClearButtonVisibility();
199 bool BaseMultipleFieldsDateAndTimeInputType::hasCustomFocusLogic() const
204 bool BaseMultipleFieldsDateAndTimeInputType::isEditControlOwnerDisabled() const
206 return element().isDisabledFormControl();
209 bool BaseMultipleFieldsDateAndTimeInputType::isEditControlOwnerReadOnly() const
211 return element().isReadOnly();
214 void BaseMultipleFieldsDateAndTimeInputType::focusAndSelectSpinButtonOwner()
216 if (DateTimeEditElement* edit = dateTimeEditElement())
217 edit->focusIfNoFocus();
220 bool BaseMultipleFieldsDateAndTimeInputType::shouldSpinButtonRespondToMouseEvents()
222 return !element().isDisabledOrReadOnly();
225 bool BaseMultipleFieldsDateAndTimeInputType::shouldSpinButtonRespondToWheelEvents()
227 if (!shouldSpinButtonRespondToMouseEvents())
229 if (DateTimeEditElement* edit = dateTimeEditElement())
230 return edit->hasFocusedField();
234 void BaseMultipleFieldsDateAndTimeInputType::spinButtonStepDown()
236 if (DateTimeEditElement* edit = dateTimeEditElement())
240 void BaseMultipleFieldsDateAndTimeInputType::spinButtonStepUp()
242 if (DateTimeEditElement* edit = dateTimeEditElement())
246 void BaseMultipleFieldsDateAndTimeInputType::spinButtonDidReleaseMouseCapture(SpinButtonElement::EventDispatch eventDispatch)
248 if (eventDispatch == SpinButtonElement::EventDispatchAllowed)
249 element().dispatchFormControlChangeEvent();
252 bool BaseMultipleFieldsDateAndTimeInputType::isPickerIndicatorOwnerDisabledOrReadOnly() const
254 return element().isDisabledOrReadOnly();
257 void BaseMultipleFieldsDateAndTimeInputType::pickerIndicatorChooseValue(const String& value)
259 if (element().isValidValue(value)) {
260 element().setValue(value, DispatchInputAndChangeEvent);
264 DateTimeEditElement* edit = this->dateTimeEditElement();
267 EventQueueScope scope;
270 if (date.parseDate(value, 0, end) && end == value.length())
271 edit->setOnlyYearMonthDay(date);
272 element().dispatchFormControlChangeEvent();
275 void BaseMultipleFieldsDateAndTimeInputType::pickerIndicatorChooseValue(double value)
277 ASSERT(std::isfinite(value) || std::isnan(value));
278 if (std::isnan(value))
279 element().setValue(emptyString(), DispatchInputAndChangeEvent);
281 element().setValueAsNumber(value, ASSERT_NO_EXCEPTION, DispatchInputAndChangeEvent);
284 bool BaseMultipleFieldsDateAndTimeInputType::setupDateTimeChooserParameters(DateTimeChooserParameters& parameters)
286 return element().setupDateTimeChooserParameters(parameters);
289 BaseMultipleFieldsDateAndTimeInputType::BaseMultipleFieldsDateAndTimeInputType(HTMLInputElement& element)
290 : BaseDateAndTimeInputType(element)
291 , m_isDestroyingShadowSubtree(false)
292 , m_pickerIndicatorIsVisible(false)
293 , m_pickerIndicatorIsAlwaysVisible(false)
297 BaseMultipleFieldsDateAndTimeInputType::~BaseMultipleFieldsDateAndTimeInputType()
300 if (SpinButtonElement* element = spinButtonElement())
301 element->removeSpinButtonOwner();
302 if (ClearButtonElement* element = clearButtonElement())
303 element->removeClearButtonOwner();
304 if (DateTimeEditElement* element = dateTimeEditElement())
305 element->removeEditControlOwner();
306 if (PickerIndicatorElement* element = pickerIndicatorElement())
307 element->removePickerIndicatorOwner();
311 String BaseMultipleFieldsDateAndTimeInputType::badInputText() const
313 return locale().queryString(blink::WebLocalizedString::ValidationBadInputForDateTime);
316 void BaseMultipleFieldsDateAndTimeInputType::blur()
318 if (DateTimeEditElement* edit = dateTimeEditElement())
322 PassRefPtr<RenderStyle> BaseMultipleFieldsDateAndTimeInputType::customStyleForRenderer(PassRefPtr<RenderStyle> originalStyle)
324 EDisplay originalDisplay = originalStyle->display();
325 EDisplay newDisplay = originalDisplay;
326 if (originalDisplay == INLINE || originalDisplay == INLINE_BLOCK)
327 newDisplay = INLINE_FLEX;
328 else if (originalDisplay == BLOCK)
330 TextDirection contentDirection = computedTextDirection();
331 if (originalStyle->direction() == contentDirection && originalDisplay == newDisplay)
332 return originalStyle;
334 RefPtr<RenderStyle> style = RenderStyle::clone(originalStyle.get());
335 style->setDirection(contentDirection);
336 style->setDisplay(newDisplay);
338 return style.release();
341 void BaseMultipleFieldsDateAndTimeInputType::createShadowSubtree()
343 ASSERT(element().shadow());
345 // Element must not have a renderer here, because if it did
346 // DateTimeEditElement::customStyleForRenderer() is called in appendChild()
347 // before the field wrapper element is created.
348 // FIXME: This code should not depend on such craziness.
349 ASSERT(!element().renderer());
351 Document& document = element().document();
352 ContainerNode* container = element().userAgentShadowRoot();
354 container->appendChild(DateTimeEditElement::create(document, *this));
355 element().updateView();
356 container->appendChild(ClearButtonElement::create(document, *this));
357 container->appendChild(SpinButtonElement::create(document, *this));
359 if (RenderTheme::theme().supportsCalendarPicker(formControlType()))
360 m_pickerIndicatorIsAlwaysVisible = true;
361 container->appendChild(PickerIndicatorElement::create(document, *this));
362 m_pickerIndicatorIsVisible = true;
363 updatePickerIndicatorVisibility();
366 void BaseMultipleFieldsDateAndTimeInputType::destroyShadowSubtree()
368 ASSERT(!m_isDestroyingShadowSubtree);
369 m_isDestroyingShadowSubtree = true;
370 if (SpinButtonElement* element = spinButtonElement())
371 element->removeSpinButtonOwner();
372 if (ClearButtonElement* element = clearButtonElement())
373 element->removeClearButtonOwner();
374 if (DateTimeEditElement* element = dateTimeEditElement())
375 element->removeEditControlOwner();
376 if (PickerIndicatorElement* element = pickerIndicatorElement())
377 element->removePickerIndicatorOwner();
379 // If a field element has focus, set focus back to the <input> itself before
380 // deleting the field. This prevents unnecessary focusout/blur events.
381 if (containsFocusedShadowElement())
384 BaseDateAndTimeInputType::destroyShadowSubtree();
385 m_isDestroyingShadowSubtree = false;
388 void BaseMultipleFieldsDateAndTimeInputType::handleFocusEvent(Element* oldFocusedElement, FocusType type)
390 DateTimeEditElement* edit = dateTimeEditElement();
391 if (!edit || m_isDestroyingShadowSubtree)
393 if (type == FocusTypeBackward) {
394 if (element().document().page())
395 element().document().page()->focusController().advanceFocus(type);
396 } else if (type == FocusTypeNone || type == FocusTypeMouse || type == FocusTypePage) {
397 edit->focusByOwner(oldFocusedElement);
399 edit->focusByOwner();
403 void BaseMultipleFieldsDateAndTimeInputType::forwardEvent(Event* event)
405 if (SpinButtonElement* element = spinButtonElement()) {
406 element->forwardEvent(event);
407 if (event->defaultHandled())
411 if (DateTimeEditElement* edit = dateTimeEditElement())
412 edit->defaultEventHandler(event);
415 void BaseMultipleFieldsDateAndTimeInputType::disabledAttributeChanged()
417 spinButtonElement()->releaseCapture();
418 clearButtonElement()->releaseCapture();
419 if (DateTimeEditElement* edit = dateTimeEditElement())
420 edit->disabledStateChanged();
423 void BaseMultipleFieldsDateAndTimeInputType::requiredAttributeChanged()
425 clearButtonElement()->releaseCapture();
426 updateClearButtonVisibility();
429 void BaseMultipleFieldsDateAndTimeInputType::handleKeydownEvent(KeyboardEvent* event)
431 if (m_pickerIndicatorIsVisible
432 && ((event->keyIdentifier() == "Down" && event->getModifierState("Alt")) || (RenderTheme::theme().shouldOpenPickerWithF4Key() && event->keyIdentifier() == "F4"))) {
433 if (PickerIndicatorElement* element = pickerIndicatorElement())
434 element->openPopup();
435 event->setDefaultHandled();
441 bool BaseMultipleFieldsDateAndTimeInputType::hasBadInput() const
443 DateTimeEditElement* edit = dateTimeEditElement();
444 return element().value().isEmpty() && edit && edit->anyEditableFieldsHaveValues();
447 AtomicString BaseMultipleFieldsDateAndTimeInputType::localeIdentifier() const
449 return element().computeInheritedLanguage();
452 void BaseMultipleFieldsDateAndTimeInputType::editControlDidChangeValueByKeyboard()
454 element().dispatchFormControlChangeEvent();
457 void BaseMultipleFieldsDateAndTimeInputType::minOrMaxAttributeChanged()
462 void BaseMultipleFieldsDateAndTimeInputType::readonlyAttributeChanged()
464 spinButtonElement()->releaseCapture();
465 clearButtonElement()->releaseCapture();
466 if (DateTimeEditElement* edit = dateTimeEditElement())
467 edit->readOnlyStateChanged();
470 void BaseMultipleFieldsDateAndTimeInputType::restoreFormControlState(const FormControlState& state)
472 DateTimeEditElement* edit = dateTimeEditElement();
475 DateTimeFieldsState dateTimeFieldsState = DateTimeFieldsState::restoreFormControlState(state);
476 edit->setValueAsDateTimeFieldsState(dateTimeFieldsState);
477 element().setValueInternal(sanitizeValue(edit->value()), DispatchNoEvent);
478 updateClearButtonVisibility();
481 FormControlState BaseMultipleFieldsDateAndTimeInputType::saveFormControlState() const
483 if (DateTimeEditElement* edit = dateTimeEditElement())
484 return edit->valueAsDateTimeFieldsState().saveFormControlState();
485 return FormControlState();
488 void BaseMultipleFieldsDateAndTimeInputType::setValue(const String& sanitizedValue, bool valueChanged, TextFieldEventBehavior eventBehavior)
490 InputType::setValue(sanitizedValue, valueChanged, eventBehavior);
491 DateTimeEditElement* edit = dateTimeEditElement();
492 if (valueChanged || (sanitizedValue.isEmpty() && edit && edit->anyEditableFieldsHaveValues())) {
493 element().updateView();
494 element().setNeedsValidityCheck();
498 void BaseMultipleFieldsDateAndTimeInputType::stepAttributeChanged()
503 void BaseMultipleFieldsDateAndTimeInputType::updateView()
505 DateTimeEditElement* edit = dateTimeEditElement();
509 DateTimeEditElement::LayoutParameters layoutParameters(element().locale(), createStepRange(AnyIsDefaultStep));
512 bool hasValue = false;
513 if (!element().suggestedValue().isNull())
514 hasValue = parseToDateComponents(element().suggestedValue(), &date);
516 hasValue = parseToDateComponents(element().value(), &date);
518 setMillisecondToDateComponents(layoutParameters.stepRange.minimum().toDouble(), &date);
520 setupLayoutParameters(layoutParameters, date);
522 DEFINE_STATIC_LOCAL(AtomicString, datetimeformatAttr, ("datetimeformat", AtomicString::ConstructFromLiteral));
523 edit->setAttribute(datetimeformatAttr, AtomicString(layoutParameters.dateTimeFormat), ASSERT_NO_EXCEPTION);
524 const AtomicString pattern = edit->fastGetAttribute(HTMLNames::patternAttr);
525 if (!pattern.isEmpty())
526 layoutParameters.dateTimeFormat = pattern;
528 if (!DateTimeFormatValidator().validateFormat(layoutParameters.dateTimeFormat, *this))
529 layoutParameters.dateTimeFormat = layoutParameters.fallbackDateTimeFormat;
532 edit->setValueAsDate(layoutParameters, date);
534 edit->setEmptyValue(layoutParameters, date);
535 updateClearButtonVisibility();
538 void BaseMultipleFieldsDateAndTimeInputType::valueAttributeChanged()
540 if (!element().hasDirtyValue())
544 void BaseMultipleFieldsDateAndTimeInputType::listAttributeTargetChanged()
546 updatePickerIndicatorVisibility();
549 void BaseMultipleFieldsDateAndTimeInputType::updatePickerIndicatorVisibility()
551 if (m_pickerIndicatorIsAlwaysVisible) {
552 showPickerIndicator();
555 if (element().hasValidDataListOptions())
556 showPickerIndicator();
558 hidePickerIndicator();
561 void BaseMultipleFieldsDateAndTimeInputType::hidePickerIndicator()
563 if (!m_pickerIndicatorIsVisible)
565 m_pickerIndicatorIsVisible = false;
566 ASSERT(pickerIndicatorElement());
567 pickerIndicatorElement()->setInlineStyleProperty(CSSPropertyDisplay, CSSValueNone);
570 void BaseMultipleFieldsDateAndTimeInputType::showPickerIndicator()
572 if (m_pickerIndicatorIsVisible)
574 m_pickerIndicatorIsVisible = true;
575 ASSERT(pickerIndicatorElement());
576 pickerIndicatorElement()->removeInlineStyleProperty(CSSPropertyDisplay);
579 bool BaseMultipleFieldsDateAndTimeInputType::shouldHaveSecondField(const DateComponents& date) const
581 StepRange stepRange = createStepRange(AnyIsDefaultStep);
582 return date.second() || date.millisecond()
583 || !stepRange.minimum().remainder(static_cast<int>(msPerMinute)).isZero()
584 || !stepRange.step().remainder(static_cast<int>(msPerMinute)).isZero();
587 void BaseMultipleFieldsDateAndTimeInputType::focusAndSelectClearButtonOwner()
592 bool BaseMultipleFieldsDateAndTimeInputType::shouldClearButtonRespondToMouseEvents()
594 return !element().isDisabledOrReadOnly() && !element().isRequired();
597 void BaseMultipleFieldsDateAndTimeInputType::clearValue()
599 RefPtrWillBeRawPtr<HTMLInputElement> input(element());
600 input->setValue("", DispatchInputAndChangeEvent);
601 input->updateClearButtonVisibility();
604 void BaseMultipleFieldsDateAndTimeInputType::updateClearButtonVisibility()
606 ClearButtonElement* clearButton = clearButtonElement();
610 if (element().isRequired() || !dateTimeEditElement()->anyEditableFieldsHaveValues()) {
611 clearButton->setInlineStyleProperty(CSSPropertyOpacity, 0.0, CSSPrimitiveValue::CSS_NUMBER);
612 clearButton->setInlineStyleProperty(CSSPropertyPointerEvents, CSSValueNone);
614 clearButton->removeInlineStyleProperty(CSSPropertyOpacity);
615 clearButton->removeInlineStyleProperty(CSSPropertyPointerEvents);
619 TextDirection BaseMultipleFieldsDateAndTimeInputType::computedTextDirection()
621 return element().locale().isRTL() ? RTL : LTR;