001package com.github.gwtbootstrap.client.ui.base; 002 003import java.util.Iterator; 004import java.util.NoSuchElementException; 005 006import com.google.gwt.user.client.DOM; 007import com.google.gwt.user.client.ui.HasOneWidget; 008import com.google.gwt.user.client.ui.HasWidgets; 009import com.google.gwt.user.client.ui.IsWidget; 010import com.google.gwt.user.client.ui.Widget; 011 012public abstract class MarkupWidget implements IsWidget, HasWidgets, 013 HasOneWidget , HasId{ 014 015 protected Widget widget; 016 private String id; 017 018 /** 019 * {@inheritDoc} 020 */ 021 public void setWidget(IsWidget w) { 022 setWidget(w == null ? null : w.asWidget()); 023 } 024 025 /** 026 * {@inheritDoc} 027 */ 028 @Override 029 public Widget asWidget() { 030 return widget; 031 } 032 033 /** 034 * {@inheritDoc} 035 */ 036 @Override 037 public Widget getWidget() { 038 return widget; 039 } 040 041 @Override 042 public void setWidget(Widget w) { 043 // Validate 044 if (w == widget) { 045 return; 046 } 047 048 widget = w; 049 050 if(widget == null ) { 051 return; 052 } 053 054 if(widget.getElement().getId() != null && !widget.getElement().getId().isEmpty()) { 055 this.id = widget.getElement().getId(); 056 return; 057 } 058 059 if(this.id != null) { 060 setId(id); 061 return; 062 } 063 064 setId(DOM.createUniqueId()); 065 } 066 067 public void add(IsWidget w) { 068 add(w.asWidget()); 069 } 070 071 /** 072 * {@inheritDoc} 073 */ 074 @Override 075 public void add(Widget w) { 076 // Can't add() more than one widget to a SimplePanel. 077 if (getWidget() != null) { 078 throw new IllegalStateException("can only contain one child widget"); 079 } 080 setWidget(w); 081 } 082 083 /** 084 * {@inheritDoc} 085 */ 086 @Override 087 public void clear() { 088 widget = null; 089 } 090 091 @Override 092 public Iterator<Widget> iterator() { 093 // Return a simple iterator that enumerates the 0 or 1 elements in this 094 // panel. 095 return new Iterator<Widget>() { 096 097 boolean hasElement = widget != null; 098 099 Widget returned = null; 100 101 public boolean hasNext() { 102 return hasElement; 103 } 104 105 public Widget next() { 106 if (!hasElement || (widget == null)) { 107 throw new NoSuchElementException(); 108 } 109 hasElement = false; 110 return (returned = widget); 111 } 112 113 public void remove() { 114 if (returned != null) { 115 MarkupWidget.this.remove(returned); 116 } 117 } 118 }; 119 } 120 121 @Override 122 public boolean remove(Widget w) { 123 // Validate. 124 if (widget != w) { 125 return false; 126 } 127 128 // Logical detach. 129 widget = null; 130 return true; 131 } 132 133 @Override 134 public void setId(String id) { 135 136 this.id = id; 137 138 if(widget != null) { 139 widget.getElement().setId(id); 140 } 141 } 142 143 @Override 144 public String getId() { 145 146 return widget != null? widget.getElement().getId() : this.id; 147 } 148 149}