e164f1ae4efcc849b58748ce4580ac645676ec5a
[potlatch2.git] / net / systemeD / controls / AutoComplete.as
1 /*
2         AutoComplete component
3         based on Adobe original but heavily bug-fixed and stripped down
4         http://www.adobe.com/cfusion/exchange/index.cfm?event=extensionDetail&extid=1047291
5         
6         Enhancements to do:
7         - up/down when field empty should show everything
8         - up (to 0) when dropdown displayed should cause it to reset to previous typed value
9         - down (past only item) when dropdown displayed should paste it
10         - shouldn't be able to leave empty fields, or those which already exist
11 */
12
13 package net.systemeD.controls {
14         import flash.events.KeyboardEvent;
15         import flash.events.Event;
16         import flash.events.FocusEvent;
17         import flash.events.MouseEvent;
18         import flash.net.SharedObject;
19         import flash.ui.Keyboard;
20         import mx.core.UIComponent;
21         import mx.controls.ComboBox;
22         import mx.controls.DataGrid;
23         import mx.controls.listClasses.ListBase;
24         import mx.collections.ArrayCollection;
25         import mx.collections.ListCollectionView;
26         import mx.events.DropdownEvent;
27         import mx.events.ListEvent;
28         import mx.events.FlexEvent;
29         import mx.managers.IFocusManagerComponent;
30
31         [Event(name="filterFunctionChange", type="flash.events.Event")]
32         [Event(name="typedTextChange", type="flash.events.Event")]
33
34         [Exclude(name="editable", kind="property")]
35
36         /**
37          *      The AutoComplete control is an enhanced 
38          *      TextInput control which pops up a list of suggestions 
39          *      based on characters entered by the user. These suggestions
40          *      are to be provided by setting the <code>dataProvider
41          *      </code> property of the control.
42          *      @mxml
43          *
44          *      <p>The <code>&lt;fc:AutoComplete&gt;</code> tag inherits all the tag attributes
45          *      of its superclass, and adds the following tag attributes:</p>
46          *
47          *      <pre>
48          *      &lt;fc:AutoComplete
49          *        <b>Properties</b>
50          *        keepLocalHistory="false"
51          *        typedText=""
52          *        filterFunction="<i>Internal filter function</i>"
53          *
54          *        <b>Events</b>
55          *        filterFunctionChange="<i>No default</i>"
56          *        typedTextChange="<i>No default</i>"
57          *      /&gt;
58          *      </pre>
59          *
60          *      @includeExample ../../../../../../docs/com/adobe/flex/extras/controls/example/AutoCompleteCountriesData/AutoCompleteCountriesData.mxml
61          *
62          *      @see mx.controls.ComboBox
63          *
64          */
65         public class AutoComplete extends ComboBox 
66         {
67
68                 //--------------------------------------------------------------------------
69                 //      Constructor
70                 //--------------------------------------------------------------------------
71
72                 public function AutoComplete() {
73                         super();
74
75                         //Make ComboBox look like a normal text field
76                         editable = true;
77
78                         setStyle("arrowButtonWidth",0);
79                         setStyle("fontWeight","normal");
80                         setStyle("cornerRadius",0);
81                         setStyle("paddingLeft",0);
82                         setStyle("paddingRight",0);
83                         rowCount = 7;
84                 }
85                 
86                 //--------------------------------------------------------------------------
87                 //      Variables
88                 //--------------------------------------------------------------------------
89
90                 private var cursorPosition:Number=0;
91                 private var prevIndex:Number = -1;
92                 private var showDropdown:Boolean=false;
93                 private var showingDropdown:Boolean=false;
94                 private var tempCollection:Object;
95                 private var dropdownClosed:Boolean=true;
96
97                 //--------------------------------------------------------------------------
98                 //      Overridden Properties
99                 //--------------------------------------------------------------------------
100
101                 override public function set editable(value:Boolean):void {
102                         //This is done to prevent user from resetting the value to false
103                         super.editable = true;
104                 }
105                 override public function set dataProvider(value:Object):void {
106                         super.dataProvider = value;
107                         tempCollection = value;
108
109                         // Big bug in Flex 3.5:
110                         //  http://www.newtriks.com/?p=935
111                         //  http://forums.adobe.com/message/2952677
112                         //  https://bugs.adobe.com/jira/browse/SDK-25567
113                         //  https://bugs.adobe.com/jira/browse/SDK-25705
114                         //  http://stackoverflow.com/questions/3006291/adobe-flex-combobox-dataprovider
115                         // We can remove this workaround if we ever move to Flex 3.6 or Flex 4
116                         var newDropDown:ListBase = dropdown;
117                         if(newDropDown) {
118                                 validateSize(true);
119                                 newDropDown.dataProvider = super.dataProvider;
120
121                                 dropdown.addEventListener(ListEvent.ITEM_CLICK, itemClickHandler, false, 0, true);
122                         }
123                 }
124
125                 override public function set labelField(value:String):void {
126                         super.labelField = value;
127                         invalidateProperties();
128                         invalidateDisplayList();
129                 }
130
131
132                 //--------------------------------------------------------------------------
133                 //      Properties
134                 //--------------------------------------------------------------------------
135
136                 private var _typedText:String="";                       // text changed by user
137                 private var typedTextChanged:Boolean;
138
139                 [Bindable("typedTextChange")]
140                 [Inspectable(category="Data")]
141                 public function get typedText():String { return _typedText; }
142
143                 public function set typedText(input:String):void {
144                         _typedText = input;
145                         typedTextChanged = true;
146                         
147                         invalidateProperties();
148                         invalidateDisplayList();
149                         dispatchEvent(new Event("typedTextChange"));
150                 }
151
152                 //--------------------------------------------------------------------------
153                 //      New event listener to restore item-click
154                 //--------------------------------------------------------------------------
155
156                 protected function itemClickHandler(event:ListEvent):void {
157                         typedTextChanged=false;
158                         textInput.text=itemToLabel(collection[event.rowIndex]);
159                         selectNextField();
160                 }
161
162                 protected function selectNextField():void {
163                         if (this.parent.parent is DataGrid) {
164                                 this.parent.parent.dispatchEvent(new FocusEvent("keyFocusChange",true,true,null,false,9));
165                         } else {
166                                 focusManager.getNextFocusManagerComponent(true).setFocus();
167                         }
168                 }
169
170                 //--------------------------------------------------------------------------
171                 //      Overridden methods
172                 //--------------------------------------------------------------------------
173
174                 override protected function commitProperties():void {
175                         super.commitProperties();
176
177                         if (dropdown) {
178                                 if (typedTextChanged) {
179                                         cursorPosition = textInput.selectionBeginIndex;
180                                         updateDataProvider();
181
182                                         if( collection.length==0 || typedText=="" || typedText==null ) {
183                                                 // no suggestions, so no dropdown
184                                                 dropdownClosed=true;
185                                                 showDropdown=false;
186                                                 showingDropdown=false;
187                                         } else {
188                                                 // show dropdown
189                                                 showDropdown = true;
190                                                 selectedIndex = 0;
191                                         }
192                                 }
193                         } else {
194                                 selectedIndex=-1
195                         }
196                 }
197                 
198                 override protected function updateDisplayList(unscaledWidth:Number, 
199                                                                   unscaledHeight:Number):void {
200
201                         super.updateDisplayList(unscaledWidth, unscaledHeight);
202                         
203                         if(selectedIndex == -1 && typedTextChanged && textInput.text!=typedText) { 
204                                 // not in menu
205                                 // trace("not in menu"); trace("- restoring to "+typedText);
206                                 textInput.text = typedText;
207                                 textInput.setSelection(textInput.text.length, textInput.text.length);
208                         } else if (dropdown && typedTextChanged && textInput.text!=typedText) {
209                                 // in menu, but user has typed
210                                 // trace("in menu, but user has typed"); trace("- restoring to "+typedText);
211                                 textInput.text = typedText;
212                                 textInput.setSelection(cursorPosition, cursorPosition);
213                         } else if (showingDropdown && textInput.text==selectedLabel) {
214                                 // force update if Flex has fucked up again
215                                 // trace("should force update");
216                                 textInput.htmlText=selectedLabel;
217                                 textInput.validateNow();
218                         } else if (showingDropdown && textInput.text!=selectedLabel && !typedTextChanged) {
219                                 // in menu, user has navigated with cursor keys/mouse
220                                 // trace("in menu, user has navigated with cursor keys/mouse");
221                                 textInput.text = selectedLabel;
222                                 textInput.setSelection(0, textInput.text.length);
223                         } else if (textInput.text!="") {
224                                 textInput.setSelection(cursorPosition, cursorPosition);
225                         }
226
227                         if (showDropdown && !dropdown.visible) {
228                                 // controls the open duration of the dropdown
229                                 super.open();
230                                 showDropdown = false;
231                                 showingDropdown = true;
232                                 dropdownClosed = false;
233                         }
234                 }
235         
236                 override protected function keyDownHandler(event:KeyboardEvent):void {
237                         super.keyDownHandler(event);
238
239                         if (event.keyCode==Keyboard.UP || event.keyCode==Keyboard.DOWN) {
240                                 typedTextChanged=false;
241                         }
242
243                         if (event.keyCode==Keyboard.ESCAPE && showingDropdown) {
244                                 // ESCAPE cancels dropdown
245                                 textInput.text = typedText;
246                                 textInput.setSelection(textInput.text.length, textInput.text.length);
247                                 showingDropdown = false;
248                                 dropdownClosed=true;
249
250                         } else if (event.keyCode == Keyboard.ENTER) {
251                                 // ENTER pressed, so select the topmost item (if it exists)
252                                 if (selectedIndex>-1) { textInput.text = selectedLabel; }
253                                 dropdownClosed=true;
254                                 
255                                 // and move on to the next field
256                                 event.stopImmediatePropagation();
257                                 selectNextField();
258
259                         } else if (event.ctrlKey && event.keyCode == Keyboard.UP) {
260                                 dropdownClosed=true;
261                         }
262                 
263                         prevIndex = selectedIndex;
264                 }
265         
266                 override public function getStyle(styleProp:String):* {
267                         if (styleProp != "openDuration") {
268                                 return super.getStyle(styleProp);
269                         } else {
270                                 if (dropdownClosed) return super.getStyle(styleProp);
271                                 else return 0;
272                         }
273                 }
274
275                 override protected function textInput_changeHandler(event:Event):void {
276                         super.textInput_changeHandler(event);
277                         typedText = text;
278                         typedTextChanged = true;
279                 }
280
281                 override protected function measure():void {
282                         super.measure();
283                         measuredWidth = mx.core.UIComponent.DEFAULT_MEASURED_WIDTH;
284                 }
285
286                 override public function set selectedIndex(value:int):void {
287                         var prevtext:String=text;
288                         super.selectedIndex=value;
289                         text=prevtext;
290                 }
291
292
293                 //----------------------------------
294                 //      filterFunction
295                 //----------------------------------
296                 /**
297                  *      A function that is used to select items that match the
298                  *      function's criteria. 
299                  *      A filterFunction is expected to have the following signature:
300                  *
301                  *      <pre>f(item:~~, text:String):Boolean</pre>
302                  *
303                  *      where the return value is <code>true</code> if the specified item
304                  *      should displayed as a suggestion. 
305                  *      Whenever there is a change in text in the AutoComplete control, this 
306                  *      filterFunction is run on each item in the <code>dataProvider</code>.
307                  *      
308                  *      <p>The default implementation for filterFunction works as follows:<br>
309                  *      If "AB" has been typed, it will display all the items matching 
310                  *      "AB~~" (ABaa, ABcc, abAc etc.).</p>
311                  *
312                  *      <p>An example usage of a customized filterFunction is when text typed
313                  *      is a regular expression and we want to display all the
314                  *      items which come in the set.</p>
315                  *
316                  *      @example
317                  *      <pre>
318                  *      public function myFilterFunction(item:~~, text:String):Boolean
319                  *      {
320                  *         public var regExp:RegExp = new RegExp(text,"");
321                  *         return regExp.test(item);
322                  *      }
323                  *      </pre>
324                  *
325                  */
326
327                 private var _filterFunction:Function = defaultFilterFunction;
328                 private var filterFunctionChanged:Boolean = true;
329
330                 [Bindable("filterFunctionChange")]
331                 [Inspectable(category="General")]
332
333                 public function get filterFunction():Function {
334                         return _filterFunction;
335                 }
336
337                 public function set filterFunction(value:Function):void {
338                         //An empty filterFunction is allowed but not a null filterFunction
339                         if(value!=null) {
340                                 _filterFunction = value;
341                                 filterFunctionChanged = true;
342
343                                 invalidateProperties();
344                                 invalidateDisplayList();
345         
346                                 dispatchEvent(new Event("filterFunctionChange"));
347                         } else {
348                                 _filterFunction = defaultFilterFunction;
349                         }
350                 }
351                                 
352                 private function defaultFilterFunction(element:*, text:String):Boolean {
353                         var label:String = itemToLabel(element);
354                         return (label.toLowerCase().substring(0,text.length) == text.toLowerCase());
355                 }
356
357                 private function templateFilterFunction(element:*):Boolean {
358                         var flag:Boolean=false;
359                         if(filterFunction!=null)
360                                 flag=filterFunction(element,typedText);
361                         return flag;
362                 }
363
364                 // Updates the dataProvider used for showing suggestions
365                 private function updateDataProvider():void {
366                         dataProvider = tempCollection;
367                         collection.filterFunction = templateFilterFunction;
368                         collection.refresh();
369                 }
370         }       
371 }