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/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/text/DateTimeFormat.h"
50 #include "platform/text/PlatformLocale.h"
51 #include "wtf/DateMath.h"
55 class DateTimeFormatValidator : public DateTimeFormat::TokenHandler {
57 DateTimeFormatValidator()
65 , m_hasSecond(false) { }
67 virtual void visitField(DateTimeFormat::FieldType, int) OVERRIDE FINAL;
68 virtual void visitLiteral(const String&) OVERRIDE FINAL { }
70 bool validateFormat(const String& format, const BaseMultipleFieldsDateAndTimeInputType&);
83 void DateTimeFormatValidator::visitField(DateTimeFormat::FieldType fieldType, int)
86 case DateTimeFormat::FieldTypeYear:
89 case DateTimeFormat::FieldTypeMonth: // Fallthrough.
90 case DateTimeFormat::FieldTypeMonthStandAlone:
93 case DateTimeFormat::FieldTypeWeekOfYear:
96 case DateTimeFormat::FieldTypeDayOfMonth:
99 case DateTimeFormat::FieldTypePeriod:
102 case DateTimeFormat::FieldTypeHour11: // Fallthrough.
103 case DateTimeFormat::FieldTypeHour12:
106 case DateTimeFormat::FieldTypeHour23: // Fallthrough.
107 case DateTimeFormat::FieldTypeHour24:
111 case DateTimeFormat::FieldTypeMinute:
114 case DateTimeFormat::FieldTypeSecond:
122 bool DateTimeFormatValidator::validateFormat(const String& format, const BaseMultipleFieldsDateAndTimeInputType& inputType)
124 if (!DateTimeFormat::parse(format, *this))
126 return inputType.isValidFormat(m_hasYear, m_hasMonth, m_hasWeek, m_hasDay, m_hasAMPM, m_hasHour, m_hasMinute, m_hasSecond);
129 DateTimeEditElement* BaseMultipleFieldsDateAndTimeInputType::dateTimeEditElement() const
131 return toDateTimeEditElement(element().userAgentShadowRoot()->getElementById(ShadowElementNames::dateTimeEdit()));
134 SpinButtonElement* BaseMultipleFieldsDateAndTimeInputType::spinButtonElement() const
136 return toSpinButtonElement(element().userAgentShadowRoot()->getElementById(ShadowElementNames::spinButton()));
139 ClearButtonElement* BaseMultipleFieldsDateAndTimeInputType::clearButtonElement() const
141 return toClearButtonElement(element().userAgentShadowRoot()->getElementById(ShadowElementNames::clearButton()));
144 PickerIndicatorElement* BaseMultipleFieldsDateAndTimeInputType::pickerIndicatorElement() const
146 return toPickerIndicatorElement(element().userAgentShadowRoot()->getElementById(ShadowElementNames::pickerIndicator()));
149 inline bool BaseMultipleFieldsDateAndTimeInputType::containsFocusedShadowElement() const
151 return element().userAgentShadowRoot()->contains(element().document().focusedElement());
154 void BaseMultipleFieldsDateAndTimeInputType::didBlurFromControl()
156 // We don't need to call blur(). This function is called when control
159 if (containsFocusedShadowElement())
161 RefPtr<HTMLInputElement> protector(element());
162 // Remove focus ring by CSS "focus" pseudo class.
163 element().setFocus(false);
166 void BaseMultipleFieldsDateAndTimeInputType::didFocusOnControl()
168 // We don't need to call focus(). This function is called when control
171 if (!containsFocusedShadowElement())
173 // Add focus ring by CSS "focus" pseudo class.
174 // FIXME: Setting the focus flag to non-focused element is too tricky.
175 element().setFocus(true);
178 void BaseMultipleFieldsDateAndTimeInputType::editControlValueChanged()
180 RefPtr<HTMLInputElement> input(element());
181 String oldValue = input->value();
182 String newValue = sanitizeValue(dateTimeEditElement()->value());
183 // Even if oldValue is null and newValue is "", we should assume they are same.
184 if ((oldValue.isEmpty() && newValue.isEmpty()) || oldValue == newValue) {
185 input->setNeedsValidityCheck();
187 input->setValueInternal(newValue, DispatchNoEvent);
188 input->setNeedsStyleRecalc(SubtreeStyleChange);
189 input->dispatchFormControlInputEvent();
190 input->dispatchFormControlChangeEvent();
192 input->notifyFormStateChanged();
193 input->updateClearButtonVisibility();
196 bool BaseMultipleFieldsDateAndTimeInputType::hasCustomFocusLogic() const
201 bool BaseMultipleFieldsDateAndTimeInputType::isEditControlOwnerDisabled() const
203 return element().isDisabledFormControl();
206 bool BaseMultipleFieldsDateAndTimeInputType::isEditControlOwnerReadOnly() const
208 return element().isReadOnly();
211 void BaseMultipleFieldsDateAndTimeInputType::focusAndSelectSpinButtonOwner()
213 if (DateTimeEditElement* edit = dateTimeEditElement())
214 edit->focusIfNoFocus();
217 bool BaseMultipleFieldsDateAndTimeInputType::shouldSpinButtonRespondToMouseEvents()
219 return !element().isDisabledOrReadOnly();
222 bool BaseMultipleFieldsDateAndTimeInputType::shouldSpinButtonRespondToWheelEvents()
224 if (!shouldSpinButtonRespondToMouseEvents())
226 if (DateTimeEditElement* edit = dateTimeEditElement())
227 return edit->hasFocusedField();
231 void BaseMultipleFieldsDateAndTimeInputType::spinButtonStepDown()
233 if (DateTimeEditElement* edit = dateTimeEditElement())
237 void BaseMultipleFieldsDateAndTimeInputType::spinButtonStepUp()
239 if (DateTimeEditElement* edit = dateTimeEditElement())
243 bool BaseMultipleFieldsDateAndTimeInputType::isPickerIndicatorOwnerDisabledOrReadOnly() const
245 return element().isDisabledOrReadOnly();
248 void BaseMultipleFieldsDateAndTimeInputType::pickerIndicatorChooseValue(const String& value)
250 if (element().isValidValue(value)) {
251 element().setValue(value, DispatchInputAndChangeEvent);
255 DateTimeEditElement* edit = this->dateTimeEditElement();
260 if (date.parseDate(value, 0, end) && end == value.length())
261 edit->setOnlyYearMonthDay(date);
264 void BaseMultipleFieldsDateAndTimeInputType::pickerIndicatorChooseValue(double value)
266 ASSERT(std::isfinite(value) || std::isnan(value));
267 if (std::isnan(value))
268 element().setValue(emptyString(), DispatchInputAndChangeEvent);
270 element().setValueAsNumber(value, ASSERT_NO_EXCEPTION, DispatchInputAndChangeEvent);
273 bool BaseMultipleFieldsDateAndTimeInputType::setupDateTimeChooserParameters(DateTimeChooserParameters& parameters)
275 return element().setupDateTimeChooserParameters(parameters);
278 BaseMultipleFieldsDateAndTimeInputType::BaseMultipleFieldsDateAndTimeInputType(HTMLInputElement& element)
279 : BaseDateAndTimeInputType(element)
280 , m_isDestroyingShadowSubtree(false)
281 , m_pickerIndicatorIsVisible(false)
282 , m_pickerIndicatorIsAlwaysVisible(false)
286 BaseMultipleFieldsDateAndTimeInputType::~BaseMultipleFieldsDateAndTimeInputType()
288 if (SpinButtonElement* element = spinButtonElement())
289 element->removeSpinButtonOwner();
290 if (ClearButtonElement* element = clearButtonElement())
291 element->removeClearButtonOwner();
292 if (DateTimeEditElement* element = dateTimeEditElement())
293 element->removeEditControlOwner();
294 if (PickerIndicatorElement* element = pickerIndicatorElement())
295 element->removePickerIndicatorOwner();
298 String BaseMultipleFieldsDateAndTimeInputType::badInputText() const
300 return locale().queryString(blink::WebLocalizedString::ValidationBadInputForDateTime);
303 void BaseMultipleFieldsDateAndTimeInputType::blur()
305 if (DateTimeEditElement* edit = dateTimeEditElement())
309 PassRefPtr<RenderStyle> BaseMultipleFieldsDateAndTimeInputType::customStyleForRenderer(PassRefPtr<RenderStyle> originalStyle)
311 EDisplay originalDisplay = originalStyle->display();
312 EDisplay newDisplay = originalDisplay;
313 if (originalDisplay == INLINE || originalDisplay == INLINE_BLOCK)
314 newDisplay = INLINE_FLEX;
315 else if (originalDisplay == BLOCK)
317 TextDirection contentDirection = element().locale().isRTL() ? RTL : LTR;
318 if (originalStyle->direction() == contentDirection && originalDisplay == newDisplay)
319 return originalStyle;
321 RefPtr<RenderStyle> style = RenderStyle::clone(originalStyle.get());
322 style->setDirection(contentDirection);
323 style->setDisplay(newDisplay);
325 return style.release();
328 void BaseMultipleFieldsDateAndTimeInputType::createShadowSubtree()
330 ASSERT(element().shadow());
332 // Element must not have a renderer here, because if it did
333 // DateTimeEditElement::customStyleForRenderer() is called in appendChild()
334 // before the field wrapper element is created.
335 // FIXME: This code should not depend on such craziness.
336 ASSERT(!element().renderer());
338 Document& document = element().document();
339 ContainerNode* container = element().userAgentShadowRoot();
341 container->appendChild(DateTimeEditElement::create(document, *this));
342 element().updateView();
343 container->appendChild(ClearButtonElement::create(document, *this));
344 container->appendChild(SpinButtonElement::create(document, *this));
346 bool shouldAddPickerIndicator = false;
347 if (InputType::themeSupportsDataListUI(this))
348 shouldAddPickerIndicator = true;
349 if (RenderTheme::theme().supportsCalendarPicker(formControlType())) {
350 shouldAddPickerIndicator = true;
351 m_pickerIndicatorIsAlwaysVisible = true;
353 if (shouldAddPickerIndicator) {
354 container->appendChild(PickerIndicatorElement::create(document, *this));
355 m_pickerIndicatorIsVisible = true;
356 updatePickerIndicatorVisibility();
360 void BaseMultipleFieldsDateAndTimeInputType::destroyShadowSubtree()
362 ASSERT(!m_isDestroyingShadowSubtree);
363 m_isDestroyingShadowSubtree = true;
364 if (SpinButtonElement* element = spinButtonElement())
365 element->removeSpinButtonOwner();
366 if (ClearButtonElement* element = clearButtonElement())
367 element->removeClearButtonOwner();
368 if (DateTimeEditElement* element = dateTimeEditElement())
369 element->removeEditControlOwner();
370 if (PickerIndicatorElement* element = pickerIndicatorElement())
371 element->removePickerIndicatorOwner();
373 // If a field element has focus, set focus back to the <input> itself before
374 // deleting the field. This prevents unnecessary focusout/blur events.
375 if (containsFocusedShadowElement())
378 BaseDateAndTimeInputType::destroyShadowSubtree();
379 m_isDestroyingShadowSubtree = false;
382 void BaseMultipleFieldsDateAndTimeInputType::handleFocusEvent(Element* oldFocusedElement, FocusType type)
384 DateTimeEditElement* edit = dateTimeEditElement();
385 if (!edit || m_isDestroyingShadowSubtree)
387 if (type == FocusTypeBackward) {
388 if (element().document().page())
389 element().document().page()->focusController().advanceFocus(type);
390 } else if (type == FocusTypeNone || type == FocusTypeMouse || type == FocusTypePage) {
391 edit->focusByOwner(oldFocusedElement);
393 edit->focusByOwner();
397 void BaseMultipleFieldsDateAndTimeInputType::forwardEvent(Event* event)
399 if (SpinButtonElement* element = spinButtonElement()) {
400 element->forwardEvent(event);
401 if (event->defaultHandled())
405 if (DateTimeEditElement* edit = dateTimeEditElement())
406 edit->defaultEventHandler(event);
409 void BaseMultipleFieldsDateAndTimeInputType::disabledAttributeChanged()
411 spinButtonElement()->releaseCapture();
412 clearButtonElement()->releaseCapture();
413 if (DateTimeEditElement* edit = dateTimeEditElement())
414 edit->disabledStateChanged();
417 void BaseMultipleFieldsDateAndTimeInputType::requiredAttributeChanged()
419 clearButtonElement()->releaseCapture();
420 updateClearButtonVisibility();
423 void BaseMultipleFieldsDateAndTimeInputType::handleKeydownEvent(KeyboardEvent* event)
425 if (m_pickerIndicatorIsVisible
426 && ((event->keyIdentifier() == "Down" && event->getModifierState("Alt")) || (RenderTheme::theme().shouldOpenPickerWithF4Key() && event->keyIdentifier() == "F4"))) {
427 if (PickerIndicatorElement* element = pickerIndicatorElement())
428 element->openPopup();
429 event->setDefaultHandled();
435 bool BaseMultipleFieldsDateAndTimeInputType::hasBadInput() const
437 DateTimeEditElement* edit = dateTimeEditElement();
438 return element().value().isEmpty() && edit && edit->anyEditableFieldsHaveValues();
441 AtomicString BaseMultipleFieldsDateAndTimeInputType::localeIdentifier() const
443 return element().computeInheritedLanguage();
446 void BaseMultipleFieldsDateAndTimeInputType::minOrMaxAttributeChanged()
451 void BaseMultipleFieldsDateAndTimeInputType::readonlyAttributeChanged()
453 spinButtonElement()->releaseCapture();
454 clearButtonElement()->releaseCapture();
455 if (DateTimeEditElement* edit = dateTimeEditElement())
456 edit->readOnlyStateChanged();
459 void BaseMultipleFieldsDateAndTimeInputType::restoreFormControlState(const FormControlState& state)
461 DateTimeEditElement* edit = dateTimeEditElement();
464 DateTimeFieldsState dateTimeFieldsState = DateTimeFieldsState::restoreFormControlState(state);
465 edit->setValueAsDateTimeFieldsState(dateTimeFieldsState);
466 element().setValueInternal(sanitizeValue(edit->value()), DispatchNoEvent);
467 updateClearButtonVisibility();
470 FormControlState BaseMultipleFieldsDateAndTimeInputType::saveFormControlState() const
472 if (DateTimeEditElement* edit = dateTimeEditElement())
473 return edit->valueAsDateTimeFieldsState().saveFormControlState();
474 return FormControlState();
477 void BaseMultipleFieldsDateAndTimeInputType::setValue(const String& sanitizedValue, bool valueChanged, TextFieldEventBehavior eventBehavior)
479 InputType::setValue(sanitizedValue, valueChanged, eventBehavior);
480 DateTimeEditElement* edit = dateTimeEditElement();
481 if (valueChanged || (sanitizedValue.isEmpty() && edit && edit->anyEditableFieldsHaveValues())) {
482 element().updateView();
483 element().setNeedsValidityCheck();
487 bool BaseMultipleFieldsDateAndTimeInputType::shouldUseInputMethod() const
492 void BaseMultipleFieldsDateAndTimeInputType::stepAttributeChanged()
497 void BaseMultipleFieldsDateAndTimeInputType::updateView()
499 DateTimeEditElement* edit = dateTimeEditElement();
503 DateTimeEditElement::LayoutParameters layoutParameters(element().locale(), createStepRange(AnyIsDefaultStep));
506 const bool hasValue = parseToDateComponents(element().value(), &date);
508 setMillisecondToDateComponents(layoutParameters.stepRange.minimum().toDouble(), &date);
510 setupLayoutParameters(layoutParameters, date);
512 const AtomicString pattern = edit->fastGetAttribute(HTMLNames::patternAttr);
513 if (!pattern.isEmpty())
514 layoutParameters.dateTimeFormat = pattern;
516 if (!DateTimeFormatValidator().validateFormat(layoutParameters.dateTimeFormat, *this))
517 layoutParameters.dateTimeFormat = layoutParameters.fallbackDateTimeFormat;
520 edit->setValueAsDate(layoutParameters, date);
522 edit->setEmptyValue(layoutParameters, date);
523 updateClearButtonVisibility();
526 void BaseMultipleFieldsDateAndTimeInputType::valueAttributeChanged()
528 if (!element().hasDirtyValue())
532 void BaseMultipleFieldsDateAndTimeInputType::listAttributeTargetChanged()
534 updatePickerIndicatorVisibility();
537 void BaseMultipleFieldsDateAndTimeInputType::updatePickerIndicatorVisibility()
539 if (m_pickerIndicatorIsAlwaysVisible) {
540 showPickerIndicator();
543 if (element().hasValidDataListOptions())
544 showPickerIndicator();
546 hidePickerIndicator();
549 void BaseMultipleFieldsDateAndTimeInputType::hidePickerIndicator()
551 if (!m_pickerIndicatorIsVisible)
553 m_pickerIndicatorIsVisible = false;
554 ASSERT(pickerIndicatorElement());
555 pickerIndicatorElement()->setInlineStyleProperty(CSSPropertyDisplay, CSSValueNone);
558 void BaseMultipleFieldsDateAndTimeInputType::showPickerIndicator()
560 if (m_pickerIndicatorIsVisible)
562 m_pickerIndicatorIsVisible = true;
563 ASSERT(pickerIndicatorElement());
564 pickerIndicatorElement()->removeInlineStyleProperty(CSSPropertyDisplay);
567 bool BaseMultipleFieldsDateAndTimeInputType::shouldHaveSecondField(const DateComponents& date) const
569 StepRange stepRange = createStepRange(AnyIsDefaultStep);
570 return date.second() || date.millisecond()
571 || !stepRange.minimum().remainder(static_cast<int>(msPerMinute)).isZero()
572 || !stepRange.step().remainder(static_cast<int>(msPerMinute)).isZero();
575 void BaseMultipleFieldsDateAndTimeInputType::focusAndSelectClearButtonOwner()
580 bool BaseMultipleFieldsDateAndTimeInputType::shouldClearButtonRespondToMouseEvents()
582 return !element().isDisabledOrReadOnly() && !element().isRequired();
585 void BaseMultipleFieldsDateAndTimeInputType::clearValue()
587 RefPtr<HTMLInputElement> input(element());
588 input->setValue("", DispatchInputAndChangeEvent);
589 input->updateClearButtonVisibility();
592 void BaseMultipleFieldsDateAndTimeInputType::updateClearButtonVisibility()
594 ClearButtonElement* clearButton = clearButtonElement();
598 if (element().isRequired() || !dateTimeEditElement()->anyEditableFieldsHaveValues()) {
599 clearButton->setInlineStyleProperty(CSSPropertyOpacity, 0.0, CSSPrimitiveValue::CSS_NUMBER);
600 clearButton->setInlineStyleProperty(CSSPropertyPointerEvents, CSSValueNone);
602 clearButton->removeInlineStyleProperty(CSSPropertyOpacity);
603 clearButton->removeInlineStyleProperty(CSSPropertyPointerEvents);
607 } // namespace WebCore