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 "CSSValueKeywords.h"
36 #include "RuntimeEnabledFeatures.h"
37 #include "core/dom/shadow/ShadowRoot.h"
38 #include "core/events/KeyboardEvent.h"
39 #include "core/events/ScopedEventQueue.h"
40 #include "core/html/HTMLDataListElement.h"
41 #include "core/html/HTMLInputElement.h"
42 #include "core/html/HTMLOptionElement.h"
43 #include "core/html/forms/DateTimeFieldsState.h"
44 #include "core/html/forms/FormController.h"
45 #include "core/html/shadow/ShadowElementNames.h"
46 #include "core/page/FocusController.h"
47 #include "core/page/Page.h"
48 #include "core/rendering/RenderTheme.h"
49 #include "platform/DateComponents.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 RefPtr<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 RefPtr<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();
269 if (date.parseDate(value, 0, end) && end == value.length())
270 edit->setOnlyYearMonthDay(date);
271 element().dispatchFormControlChangeEvent();
274 void BaseMultipleFieldsDateAndTimeInputType::pickerIndicatorChooseValue(double value)
276 ASSERT(std::isfinite(value) || std::isnan(value));
277 if (std::isnan(value))
278 element().setValue(emptyString(), DispatchInputAndChangeEvent);
280 element().setValueAsNumber(value, ASSERT_NO_EXCEPTION, DispatchInputAndChangeEvent);
283 bool BaseMultipleFieldsDateAndTimeInputType::setupDateTimeChooserParameters(DateTimeChooserParameters& parameters)
285 return element().setupDateTimeChooserParameters(parameters);
288 BaseMultipleFieldsDateAndTimeInputType::BaseMultipleFieldsDateAndTimeInputType(HTMLInputElement& element)
289 : BaseDateAndTimeInputType(element)
290 , m_isDestroyingShadowSubtree(false)
291 , m_pickerIndicatorIsVisible(false)
292 , m_pickerIndicatorIsAlwaysVisible(false)
296 BaseMultipleFieldsDateAndTimeInputType::~BaseMultipleFieldsDateAndTimeInputType()
299 if (SpinButtonElement* element = spinButtonElement())
300 element->removeSpinButtonOwner();
301 if (ClearButtonElement* element = clearButtonElement())
302 element->removeClearButtonOwner();
303 if (DateTimeEditElement* element = dateTimeEditElement())
304 element->removeEditControlOwner();
305 if (PickerIndicatorElement* element = pickerIndicatorElement())
306 element->removePickerIndicatorOwner();
310 String BaseMultipleFieldsDateAndTimeInputType::badInputText() const
312 return locale().queryString(blink::WebLocalizedString::ValidationBadInputForDateTime);
315 void BaseMultipleFieldsDateAndTimeInputType::blur()
317 if (DateTimeEditElement* edit = dateTimeEditElement())
321 PassRefPtr<RenderStyle> BaseMultipleFieldsDateAndTimeInputType::customStyleForRenderer(PassRefPtr<RenderStyle> originalStyle)
323 EDisplay originalDisplay = originalStyle->display();
324 EDisplay newDisplay = originalDisplay;
325 if (originalDisplay == INLINE || originalDisplay == INLINE_BLOCK)
326 newDisplay = INLINE_FLEX;
327 else if (originalDisplay == BLOCK)
329 TextDirection contentDirection = element().locale().isRTL() ? RTL : LTR;
330 if (originalStyle->direction() == contentDirection && originalDisplay == newDisplay)
331 return originalStyle;
333 RefPtr<RenderStyle> style = RenderStyle::clone(originalStyle.get());
334 style->setDirection(contentDirection);
335 style->setDisplay(newDisplay);
337 return style.release();
340 void BaseMultipleFieldsDateAndTimeInputType::createShadowSubtree()
342 ASSERT(element().shadow());
344 // Element must not have a renderer here, because if it did
345 // DateTimeEditElement::customStyleForRenderer() is called in appendChild()
346 // before the field wrapper element is created.
347 // FIXME: This code should not depend on such craziness.
348 ASSERT(!element().renderer());
350 Document& document = element().document();
351 ContainerNode* container = element().userAgentShadowRoot();
353 container->appendChild(DateTimeEditElement::create(document, *this));
354 element().updateView();
355 container->appendChild(ClearButtonElement::create(document, *this));
356 container->appendChild(SpinButtonElement::create(document, *this));
358 if (RenderTheme::theme().supportsCalendarPicker(formControlType()))
359 m_pickerIndicatorIsAlwaysVisible = true;
360 container->appendChild(PickerIndicatorElement::create(document, *this));
361 m_pickerIndicatorIsVisible = true;
362 updatePickerIndicatorVisibility();
365 void BaseMultipleFieldsDateAndTimeInputType::destroyShadowSubtree()
367 ASSERT(!m_isDestroyingShadowSubtree);
368 m_isDestroyingShadowSubtree = true;
369 if (SpinButtonElement* element = spinButtonElement())
370 element->removeSpinButtonOwner();
371 if (ClearButtonElement* element = clearButtonElement())
372 element->removeClearButtonOwner();
373 if (DateTimeEditElement* element = dateTimeEditElement())
374 element->removeEditControlOwner();
375 if (PickerIndicatorElement* element = pickerIndicatorElement())
376 element->removePickerIndicatorOwner();
378 // If a field element has focus, set focus back to the <input> itself before
379 // deleting the field. This prevents unnecessary focusout/blur events.
380 if (containsFocusedShadowElement())
383 BaseDateAndTimeInputType::destroyShadowSubtree();
384 m_isDestroyingShadowSubtree = false;
387 void BaseMultipleFieldsDateAndTimeInputType::handleFocusEvent(Element* oldFocusedElement, FocusType type)
389 DateTimeEditElement* edit = dateTimeEditElement();
390 if (!edit || m_isDestroyingShadowSubtree)
392 if (type == FocusTypeBackward) {
393 if (element().document().page())
394 element().document().page()->focusController().advanceFocus(type);
395 } else if (type == FocusTypeNone || type == FocusTypeMouse || type == FocusTypePage) {
396 edit->focusByOwner(oldFocusedElement);
398 edit->focusByOwner();
402 void BaseMultipleFieldsDateAndTimeInputType::forwardEvent(Event* event)
404 if (SpinButtonElement* element = spinButtonElement()) {
405 element->forwardEvent(event);
406 if (event->defaultHandled())
410 if (DateTimeEditElement* edit = dateTimeEditElement())
411 edit->defaultEventHandler(event);
414 void BaseMultipleFieldsDateAndTimeInputType::disabledAttributeChanged()
416 spinButtonElement()->releaseCapture();
417 clearButtonElement()->releaseCapture();
418 if (DateTimeEditElement* edit = dateTimeEditElement())
419 edit->disabledStateChanged();
422 void BaseMultipleFieldsDateAndTimeInputType::requiredAttributeChanged()
424 clearButtonElement()->releaseCapture();
425 updateClearButtonVisibility();
428 void BaseMultipleFieldsDateAndTimeInputType::handleKeydownEvent(KeyboardEvent* event)
430 if (m_pickerIndicatorIsVisible
431 && ((event->keyIdentifier() == "Down" && event->getModifierState("Alt")) || (RenderTheme::theme().shouldOpenPickerWithF4Key() && event->keyIdentifier() == "F4"))) {
432 if (PickerIndicatorElement* element = pickerIndicatorElement())
433 element->openPopup();
434 event->setDefaultHandled();
440 bool BaseMultipleFieldsDateAndTimeInputType::hasBadInput() const
442 DateTimeEditElement* edit = dateTimeEditElement();
443 return element().value().isEmpty() && edit && edit->anyEditableFieldsHaveValues();
446 AtomicString BaseMultipleFieldsDateAndTimeInputType::localeIdentifier() const
448 return element().computeInheritedLanguage();
451 void BaseMultipleFieldsDateAndTimeInputType::editControlDidChangeValueByKeyboard()
453 element().dispatchFormControlChangeEvent();
456 void BaseMultipleFieldsDateAndTimeInputType::minOrMaxAttributeChanged()
461 void BaseMultipleFieldsDateAndTimeInputType::readonlyAttributeChanged()
463 spinButtonElement()->releaseCapture();
464 clearButtonElement()->releaseCapture();
465 if (DateTimeEditElement* edit = dateTimeEditElement())
466 edit->readOnlyStateChanged();
469 void BaseMultipleFieldsDateAndTimeInputType::restoreFormControlState(const FormControlState& state)
471 DateTimeEditElement* edit = dateTimeEditElement();
474 DateTimeFieldsState dateTimeFieldsState = DateTimeFieldsState::restoreFormControlState(state);
475 edit->setValueAsDateTimeFieldsState(dateTimeFieldsState);
476 element().setValueInternal(sanitizeValue(edit->value()), DispatchNoEvent);
477 updateClearButtonVisibility();
480 FormControlState BaseMultipleFieldsDateAndTimeInputType::saveFormControlState() const
482 if (DateTimeEditElement* edit = dateTimeEditElement())
483 return edit->valueAsDateTimeFieldsState().saveFormControlState();
484 return FormControlState();
487 void BaseMultipleFieldsDateAndTimeInputType::setValue(const String& sanitizedValue, bool valueChanged, TextFieldEventBehavior eventBehavior)
489 InputType::setValue(sanitizedValue, valueChanged, eventBehavior);
490 DateTimeEditElement* edit = dateTimeEditElement();
491 if (valueChanged || (sanitizedValue.isEmpty() && edit && edit->anyEditableFieldsHaveValues())) {
492 element().updateView();
493 element().setNeedsValidityCheck();
497 bool BaseMultipleFieldsDateAndTimeInputType::shouldUseInputMethod() const
502 void BaseMultipleFieldsDateAndTimeInputType::stepAttributeChanged()
507 void BaseMultipleFieldsDateAndTimeInputType::updateView()
509 DateTimeEditElement* edit = dateTimeEditElement();
513 DateTimeEditElement::LayoutParameters layoutParameters(element().locale(), createStepRange(AnyIsDefaultStep));
516 bool hasValue = false;
517 if (!element().suggestedValue().isNull())
518 hasValue = parseToDateComponents(element().suggestedValue(), &date);
520 hasValue = parseToDateComponents(element().value(), &date);
522 setMillisecondToDateComponents(layoutParameters.stepRange.minimum().toDouble(), &date);
524 setupLayoutParameters(layoutParameters, date);
526 DEFINE_STATIC_LOCAL(AtomicString, datetimeformatAttr, ("datetimeformat", AtomicString::ConstructFromLiteral));
527 edit->setAttribute(datetimeformatAttr, AtomicString(layoutParameters.dateTimeFormat), ASSERT_NO_EXCEPTION);
528 const AtomicString pattern = edit->fastGetAttribute(HTMLNames::patternAttr);
529 if (!pattern.isEmpty())
530 layoutParameters.dateTimeFormat = pattern;
532 if (!DateTimeFormatValidator().validateFormat(layoutParameters.dateTimeFormat, *this))
533 layoutParameters.dateTimeFormat = layoutParameters.fallbackDateTimeFormat;
536 edit->setValueAsDate(layoutParameters, date);
538 edit->setEmptyValue(layoutParameters, date);
539 updateClearButtonVisibility();
542 void BaseMultipleFieldsDateAndTimeInputType::valueAttributeChanged()
544 if (!element().hasDirtyValue())
548 void BaseMultipleFieldsDateAndTimeInputType::listAttributeTargetChanged()
550 updatePickerIndicatorVisibility();
553 void BaseMultipleFieldsDateAndTimeInputType::updatePickerIndicatorVisibility()
555 if (m_pickerIndicatorIsAlwaysVisible) {
556 showPickerIndicator();
559 if (element().hasValidDataListOptions())
560 showPickerIndicator();
562 hidePickerIndicator();
565 void BaseMultipleFieldsDateAndTimeInputType::hidePickerIndicator()
567 if (!m_pickerIndicatorIsVisible)
569 m_pickerIndicatorIsVisible = false;
570 ASSERT(pickerIndicatorElement());
571 pickerIndicatorElement()->setInlineStyleProperty(CSSPropertyDisplay, CSSValueNone);
574 void BaseMultipleFieldsDateAndTimeInputType::showPickerIndicator()
576 if (m_pickerIndicatorIsVisible)
578 m_pickerIndicatorIsVisible = true;
579 ASSERT(pickerIndicatorElement());
580 pickerIndicatorElement()->removeInlineStyleProperty(CSSPropertyDisplay);
583 bool BaseMultipleFieldsDateAndTimeInputType::shouldHaveSecondField(const DateComponents& date) const
585 StepRange stepRange = createStepRange(AnyIsDefaultStep);
586 return date.second() || date.millisecond()
587 || !stepRange.minimum().remainder(static_cast<int>(msPerMinute)).isZero()
588 || !stepRange.step().remainder(static_cast<int>(msPerMinute)).isZero();
591 void BaseMultipleFieldsDateAndTimeInputType::focusAndSelectClearButtonOwner()
596 bool BaseMultipleFieldsDateAndTimeInputType::shouldClearButtonRespondToMouseEvents()
598 return !element().isDisabledOrReadOnly() && !element().isRequired();
601 void BaseMultipleFieldsDateAndTimeInputType::clearValue()
603 RefPtr<HTMLInputElement> input(element());
604 input->setValue("", DispatchInputAndChangeEvent);
605 input->updateClearButtonVisibility();
608 void BaseMultipleFieldsDateAndTimeInputType::updateClearButtonVisibility()
610 ClearButtonElement* clearButton = clearButtonElement();
614 if (element().isRequired() || !dateTimeEditElement()->anyEditableFieldsHaveValues()) {
615 clearButton->setInlineStyleProperty(CSSPropertyOpacity, 0.0, CSSPrimitiveValue::CSS_NUMBER);
616 clearButton->setInlineStyleProperty(CSSPropertyPointerEvents, CSSValueNone);
618 clearButton->removeInlineStyleProperty(CSSPropertyOpacity);
619 clearButton->removeInlineStyleProperty(CSSPropertyPointerEvents);
623 } // namespace WebCore