View Javadoc

1   package org.kuali.student.common.ui.client.widgets;
2   
3   import java.util.ArrayList;
4   import java.util.List;
5   
6   import org.kuali.student.common.assembly.data.Data;
7   import org.kuali.student.common.assembly.data.Data.DataValue;
8   import org.kuali.student.common.assembly.data.Data.Value;
9   import org.kuali.student.common.ui.client.application.Application;
10  import org.kuali.student.common.ui.client.configurable.mvc.sections.ValidationMessagePanel;
11  import org.kuali.student.common.ui.client.mvc.Callback;
12  import org.kuali.student.common.ui.client.mvc.HasDataValue;
13  import org.kuali.student.common.ui.client.util.Elements;
14  import org.kuali.student.common.ui.client.widgets.field.layout.element.AbbrButton;
15  import org.kuali.student.common.ui.client.widgets.field.layout.element.AbbrButton.AbbrButtonType;
16  import org.kuali.student.common.ui.client.widgets.field.layout.element.SpanPanel;
17  import org.kuali.student.common.validation.dto.ValidationResultInfo;
18  import org.kuali.student.common.validation.dto.ValidationResultInfo.ErrorLevel;
19  
20  import com.google.gwt.event.dom.client.ClickEvent;
21  import com.google.gwt.event.dom.client.ClickHandler;
22  import com.google.gwt.event.logical.shared.CloseEvent;
23  import com.google.gwt.event.logical.shared.CloseHandler;
24  import com.google.gwt.event.logical.shared.HasCloseHandlers;
25  import com.google.gwt.event.shared.HandlerRegistration;
26  import com.google.gwt.user.client.ui.Anchor;
27  import com.google.gwt.user.client.ui.Composite;
28  import com.google.gwt.user.client.ui.FlowPanel;
29  import com.google.gwt.user.client.ui.HTMLPanel;
30  import com.google.gwt.user.client.ui.Panel;
31  
32  public class KSItemLabel extends Composite implements HasCloseHandlers<KSItemLabel>, HasDataValue {
33  
34      private final String id = HTMLPanel.createUniqueId();
35      private final String contentId = HTMLPanel.createUniqueId();
36  //    private final String detaillsLinkId = HTMLPanel.createUniqueId();
37      private final String removeLinkId = HTMLPanel.createUniqueId();
38      private final String backgroundId = HTMLPanel.createUniqueId();
39      private final String PANEL_CONTENT_OPEN = "<span id='" + contentId + "'></span>";
40      private final String PANEL_CONTENT_REMOVE_LINK = "<span class='ks-selected-list-value-remove' id='" + removeLinkId + "'></span>"; 
41  //    private final String PANEL_CONTENT_DETAILS = "<span class='gwt-Anchor' style='position: absolute; right: 25px; top: 1px;' id='" + detaillsLinkId + "'></span>";
42      private final String PANEL_CONTENT_BACKGROUND = "<div id='" + backgroundId + "' class='ks-selected-list-value-container'></div>";
43      private Panel mainPanel;
44      private HTMLPanel panel;
45      private AbbrButton delete = new AbbrButton(AbbrButtonType.DELETE);
46      private Anchor viewDetails = new Anchor("View");
47      private DataHelper dataHelper;
48      private Data data;
49      private List<Callback<Value>> valueChangeCallbacks =
50          new ArrayList<Callback<Value>>();
51      private String deletedKey;
52      // the instanceId is used to identify instances.
53      private static int classInstanceId = -1;
54      public int instanceId;
55      
56      ValidationMessagePanel validationPanel = new ValidationMessagePanel();
57  	private ErrorLevel status = ErrorLevel.OK;
58  	
59      public KSItemLabel(boolean canEdit, DataHelper dataParser) {
60          init(canEdit, false, dataParser);
61      }
62      
63      public KSItemLabel(boolean canEdit, boolean hasDetails, DataHelper dataParser) {
64          init(canEdit, hasDetails, dataParser);
65      }
66  
67      private void init(boolean canEdit, boolean hasDetails, DataHelper dataParser) {
68          classInstanceId++;
69          instanceId = classInstanceId;
70          mainPanel = new FlowPanel();
71          mainPanel.setStyleName("ks-selected-list-value");
72          panel = new HTMLPanel(PANEL_CONTENT_OPEN + PANEL_CONTENT_BACKGROUND);
73          panel.getElement().setId(id);
74          this.dataHelper = dataParser;
75          mainPanel.add(panel);
76          if (hasDetails) {
77              viewDetails.getElement().getStyle().setProperty("position", "absolute");
78              viewDetails.getElement().getStyle().setProperty("right", "25px");
79              viewDetails.getElement().getStyle().setProperty("top", "1px");
80              mainPanel.add(viewDetails);
81          }
82          if(canEdit) {
83              delete.getElement().getStyle().setProperty("position", "absolute");
84              delete.getElement().getStyle().setProperty("right", "3px");
85              delete.getElement().getStyle().setProperty("top", "8px");
86              mainPanel.add(delete);
87              initDeleteHandlers();
88              mainPanel.add(validationPanel);
89          }
90          String labelText = "";
91          panel.getElementById(contentId).setInnerText(labelText);
92          panel.setVisible(false);
93          mainPanel.setVisible(false);
94          super.initWidget(mainPanel);
95      }
96      
97      @Override
98      public HandlerRegistration addCloseHandler(CloseHandler<KSItemLabel> handler) {
99          return addHandler(handler, CloseEvent.getType());
100     }
101 
102     @Override
103     public void addValueChangeCallback(Callback<Value> callback) {
104         valueChangeCallbacks.add(callback);
105     }
106 
107     private void callHandlers() {
108         if (valueChangeCallbacks != null) {
109 //            MyGwtEvent myEvent = new MyGwtEvent(getValue());
110             for (Callback<Data.Value> handler : valueChangeCallbacks) {
111                 handler.exec(getValue());
112             }
113         }
114     }
115 
116     @Override
117     public Value getValue() {
118         DataValue result = new DataValue(data);
119         return result;
120     }
121 
122     @Override
123     public void setValue(Value value) {
124         deletedKey = null;
125         if (value == null) {
126             this.data = null;
127         } else {
128             this.data = value.get();
129         }
130         callHandlers();
131         redraw();
132     }
133     
134     public String getKey() {
135         return dataHelper.getKey(data);
136     }
137     
138     public String getDisplayText() {
139         if (data == null) {
140             return null;
141         }
142         return dataHelper.parse(data);
143     }
144     
145     private String nvl(String inString) {
146         return (inString == null)? "" : inString;
147     }
148     
149     private void redraw() {
150         String labelText = null;
151         labelText = dataHelper.parse(data);
152         panel.getElementById(contentId).setInnerHTML(nvl(labelText));
153         panel.setVisible(true);
154         mainPanel.setVisible(true);
155     }
156 
157     private void initDeleteHandlers() {
158         //DOM.sinkEvents(panel.getElementById(removeLinkId), Event.ONCLICK);
159         delete.addClickHandler(new ClickHandler() {
160             @Override
161             public void onClick(ClickEvent event) {
162             	doRemove();
163             }
164         });
165     }
166 
167     public HandlerRegistration addShowDetailsHandler(ClickHandler clickHandler) {
168         return viewDetails.addClickHandler(clickHandler);
169     }
170 
171     private void doRemove() {
172 //        TODO
173 //        selectedValues.remove(this);
174 //        removedValues.add(this);
175 //        valuesPanel.remove(this);
176         deletedKey = dataHelper.getKey(data);
177         data = null;
178         redraw();
179         callHandlers();
180         CloseEvent.fire(this, this);
181     }
182     
183     public String getDeletedKey() {
184         return deletedKey;
185     }
186 
187     public void setHighlighted(boolean highlighted) {
188         if (highlighted) {
189             Elements.fadeIn(panel.getElementById(backgroundId), 250, 100, new Elements.EmptyFadeCallback());
190 //            Elements.fadeIn(mainPanel, 250, 100, new Elements.EmptyFadeCallback());
191         } else {
192             Elements.fadeOut(panel.getElementById(backgroundId), 1000, 0, new Elements.EmptyFadeCallback());   
193 //            Elements.fadeOut(mainPanel, 1000, 0, new Elements.EmptyFadeCallback());   
194         }
195     }
196     
197     public void removeHighlight(){
198     	Elements.setOpacity(panel.getElementById(backgroundId), 0);
199     }
200 
201     @Override
202     public boolean equals(Object obj) {
203         KSItemLabel item2 = null;
204         boolean result = false;
205         try {
206             item2 = (KSItemLabel) obj;
207         } catch (Exception e) {
208             return false;
209         }
210         if (item2 != null && nullSafeEquals(getKey(), item2.getKey()) &&
211                 nullSafeEquals(getDisplayText(), item2.getDisplayText())) {
212             result = true;
213         }
214         return result;
215     }
216     
217     
218     
219     private boolean nullSafeEquals(String str1, String str2) {
220         boolean result = false;
221         String tempStr1 = (str1 == null)? "" : str1;
222         String tempStr2 = (str2 == null)? "" : str2;
223         result = tempStr1.equals(tempStr2);
224         return result;
225     }
226 
227     @Override
228     public int hashCode() {
229         String key = getKey();
230         String displayText = getDisplayText();
231         key = (key == null)? "" : key;
232         displayText = (displayText == null)? "" : displayText;
233         return key.hashCode() + displayText.hashCode();
234     }
235     
236     
237 	/**
238 	 * Clears validation error and highlighting that may exist on this panel
239 	 */
240 	public void clearValidationErrors(){
241 		this.setErrorState(false);
242 		if(validationPanel != null){
243 			this.validationPanel.clearErrors();
244 		}
245 	}
246 
247 	/**
248 	 * Clears validation warnings and highlighting that may exist on this panel
249 	 */
250 	public void clearValidationWarnings(){
251 		this.setWarnState(false);
252 		if(validationPanel != null){
253 			this.validationPanel.clearWarnings();
254 		}
255 	}
256     
257 	/**
258 	 * Processes a validation result and adds an appropriate message, if needed
259 	 * @param vr
260 	 * @return
261 	 */
262 	public ErrorLevel processValidationResult(ValidationResultInfo vr, String fieldName) {
263 		//Check if this field is responsible for processing its own validation results
264 		status = ErrorLevel.OK;
265 
266 		if(vr.getLevel() == ErrorLevel.ERROR){
267 			String message = Application.getApplicationContext().getUILabel("validation", vr.getMessage());
268 			this.addValidationErrorMessage(message,fieldName);
269 			
270 			if(status.getLevel() < ErrorLevel.ERROR.getLevel()){
271 				status = vr.getLevel();
272 			}
273 		}
274 		else if(vr.getLevel() == ErrorLevel.WARN){
275 			String message = Application.getApplicationContext().getUILabel("validation", vr.getMessage());
276 			this.addValidationWarningMessage(message,fieldName);
277 			
278 			if(status.getLevel() < ErrorLevel.WARN.getLevel()){
279 				status = vr.getLevel();			
280 			}
281 		}
282 		else{
283 			//TODO does nothing on ok, ok is not currently used
284 		}
285 		return status;
286 	}
287     
288 	/**
289 	 * Add a validation message to this fields validation panel as defined by setValidationPanel.
290 	 * @param text
291 	 */
292 	public void addValidationErrorMessage(String text, String fieldName){
293 		if(validationPanel != null){
294 			KSLabel message;
295 			if(fieldName != null && !fieldName.trim().equals("")){
296 				message = new KSLabel(fieldName + " - " + text);
297 			}
298 			else{
299 				message = new KSLabel(text);
300 			}
301 			this.setErrorState(true);
302 			message.setStyleName("ks-form-error-label");
303 			this.validationPanel.addErrorMessage(message);
304 		}
305 	}
306 
307 	/**
308 	 * Add a validation message to this fields validation panel as defined by setValidationPanel.
309 	 * @param text
310 	 */
311 	public void addValidationWarningMessage(String text, String fieldName){
312 		if(validationPanel != null){
313 			SpanPanel message = new SpanPanel();
314 			if(fieldName != null && !fieldName.trim().equals("")){
315 				message.setHTML("<b> Warning </b> " + fieldName + " - " + text);
316 			}
317 			else{
318 				message.setHTML("<b> Warning </b> " + text);
319 			}
320 			message.setStyleName("ks-form-warn-label");
321 			//Only set field styling to warn, when no errors
322 			this.setWarnState((status != ErrorLevel.ERROR));
323 			this.validationPanel.addWarnMessage(message);
324 		}
325 	}
326 	
327 	/**
328 	 * Turn on/off styling for errors on field element
329 	 * 
330 	 * @param error When true turns on error styling, when false turns off error styling
331 	 */
332 	public void setErrorState(boolean error){
333 		if(error){
334 			//fieldTitle.addStyleName("invalid");
335 			if(mainPanel != null){
336 				mainPanel.addStyleName("error");
337 			}
338 			//When there is an error, don't use warning style
339 			setWarnState(false);
340 		}
341 		else{
342 			//fieldTitle.removeStyleName("invalid");
343 			if(mainPanel != null){
344 				mainPanel.removeStyleName("error");
345 			}
346 			//Reset earn state, in case there are warnings
347 			setWarnState(validationPanel.hasWarnings());
348 		}
349 	}
350 	
351 	/**
352 	 * Turn on/off styling for warnings on field element
353 	 * 
354 	 * @param warn When true turns on warning styling, when false turns off warning styling
355 	 */
356 	public void setWarnState(boolean warn){
357 		if(warn){
358 			//fieldTitle.addStyleName("invalid");
359 			if(mainPanel != null){
360 				mainPanel.addStyleName("warning");
361 			}
362 
363 
364 		}
365 		else{
366 			//fieldTitle.removeStyleName("invalid");
367 			if(mainPanel != null){
368 				mainPanel.removeStyleName("warning");
369 			}
370 
371 		}
372 	}
373 }