litesoft
@ 635
litesoft / trunk / GWT_Sandbox / FormEngine / src / com / temp / client / foundation / widget / NameToID.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 |
package com.temp.client.foundation.widget; import com.google.gwt.user.client.ui.HasName; import com.google.gwt.user.client.ui.Widget; import com.temp.shared.utils.StringUtils; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public final class NameToID { private Map<String, List<Widget>> widgetsById = new HashMap<String, List<Widget>>(); private String suffix; public static void on(HasName... widgets) { if ((widgets != null) && (widgets.length != 0)) { new NameToID().add(widgets).applyIDs(); } } public NameToID() { suffix = ""; } public NameToID(String suffix) { this.suffix = StringUtils.deNull(suffix).trim(); } public NameToID add(List<HasName> widgets) { if (widgets != null) for (HasName widget : widgets) { tryAdd(widget); } return this; } public NameToID add(HasName... widgets) { if (widgets != null) for (HasName widget : widgets) { tryAdd(widget); } return this; } public NameToID tryAdd(Widget widget) { if (widget instanceof HasName) { tryAdd((HasName)widget); } return this; } private void tryAdd(HasName widget) { if (widget instanceof Widget) { String id = extractId(widget); if (id != null) { add((Widget) widget, id + suffix); } } } public void applyIDs() { for (Map.Entry<String, List<Widget>> widgetByName : widgetsById.entrySet()) { applyIDs(widgetByName.getValue(), widgetByName.getKey()); } } private void add(Widget widget, String id) { List<Widget> widgets = widgetsById.get(id); if (widgets == null) { widgetsById.put(id, widgets = new ArrayList<Widget>()); } widgets.add(widget); } private String extractId(HasName widget) { if (widget instanceof HasIdOverride) { return StringUtils.noEmpty(((HasIdOverride) widget).getIdOverride()); } return StringUtils.noEmpty(widget.getName()); } private void applyIDs(List<Widget> widgets, String id) { if (widgets.size() == 1) { applyID(widgets.get(0), id); return; } for (int i = 0; i < widgets.size(); ) { Widget widget = widgets.get(i++); applyID(widget, id + i); } } private void applyID(Widget widget, String id) { if (widget instanceof IdSettable) { ((IdSettable) widget).setId(id); } else { widget.getElement().setId(id); } } } |