001 // Copyright 2008, 2010 The Apache Software Foundation
002 //
003 // Licensed under the Apache License, Version 2.0 (the "License");
004 // you may not use this file except in compliance with the License.
005 // You may obtain a copy of the License at
006 //
007 // http://www.apache.org/licenses/LICENSE-2.0
008 //
009 // Unless required by applicable law or agreed to in writing, software
010 // distributed under the License is distributed on an "AS IS" BASIS,
011 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
012 // See the License for the specific language governing permissions and
013 // limitations under the License.
014
015 package org.apache.tapestry5.internal.util;
016
017 import org.apache.tapestry5.Field;
018 import org.apache.tapestry5.FieldFocusPriority;
019 import org.apache.tapestry5.ValidationDecorator;
020 import org.apache.tapestry5.ValidationTracker;
021 import org.apache.tapestry5.services.javascript.JavaScriptSupport;
022
023 /**
024 * Used by {@link org.apache.tapestry5.corelib.components.Form} to determine which fields will be focused and a what
025 * priority.
026 */
027 public class AutofocusValidationDecorator extends ValidationDecoratorWrapper
028 {
029 private final ValidationTracker tracker;
030
031 private final JavaScriptSupport jsSupport;
032
033 public AutofocusValidationDecorator(ValidationDecorator delegate, ValidationTracker tracker,
034 JavaScriptSupport javascriptSupport)
035 {
036 super(delegate);
037 this.tracker = tracker;
038 this.jsSupport = javascriptSupport;
039 }
040
041 @Override
042 public void insideField(Field field)
043 {
044 super.insideField(field);
045
046 if (!field.isDisabled())
047 {
048 jsSupport.autofocus(getPriority(field), field.getClientId());
049 }
050 }
051
052 private FieldFocusPriority getPriority(Field field)
053 {
054 if (tracker.inError(field))
055 return FieldFocusPriority.IN_ERROR;
056
057 if (field.isRequired())
058 return FieldFocusPriority.REQUIRED;
059
060 return FieldFocusPriority.OPTIONAL;
061 }
062 }