-
Notifications
You must be signed in to change notification settings - Fork 333
/
CPTokenField.j
executable file
·1270 lines (1008 loc) · 40.4 KB
/
CPTokenField.j
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* CPTokenField.j
* AppKit
*
* Created by Klaas Pieter Annema.
* Copyright 2008, 280 North, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
@import <Foundation/CPCharacterSet.j>
@import <Foundation/CPIndexSet.j>
@import <Foundation/CPTimer.j>
@import "CPButton.j"
@import "CPScrollView.j"
@import "CPTextField.j"
@import "CPTableView.j"
@import "CPWindow.j"
@import "_CPAutocompleteMenu.j"
#if PLATFORM(DOM)
var CPTokenFieldDOMInputElement = nil,
CPTokenFieldDOMPasswordInputElement = nil,
CPTokenFieldDOMStandardInputElement = nil,
CPTokenFieldInputOwner = nil,
CPTokenFieldTextDidChangeValue = nil,
CPTokenFieldInputResigning = NO,
CPTokenFieldInputDidBlur = NO,
CPTokenFieldInputIsActive = NO,
CPTokenFieldCachedSelectStartFunction = nil,
CPTokenFieldCachedDragFunction = nil,
CPTokenFieldFocusInput = NO,
CPTokenFieldBlurFunction = nil,
CPTokenFieldKeyUpFunction = nil,
CPTokenFieldKeyPressFunction = nil,
CPTokenFieldKeyDownFunction = nil;
#endif
var CPScrollDestinationNone = 0,
CPScrollDestinationLeft = 1,
CPScrollDestinationRight = 2;
@implementation CPTokenField : CPTextField
{
CPScrollView _tokenScrollView;
int _shouldScrollTo;
CPRange _selectedRange;
_CPAutocompleteMenu _autocompleteMenu;
CPTimeInterval _completionDelay;
CPCharacterSet _tokenizingCharacterSet @accessors(property=tokenizingCharacterSet);
CPEvent _mouseDownEvent;
BOOL _preventResign;
BOOL _shouldNotifyTarget;
}
+ (CPCharacterSet)defaultTokenizingCharacterSet
{
return [CPCharacterSet characterSetWithCharactersInString:@","];
}
+ (CPString)defaultThemeClass
{
return "tokenfield";
}
- (id)initWithFrame:(CPRect)frame
{
if (self = [super initWithFrame:frame])
{
_completionDelay = [CPTokenField defaultCompletionDelay];
_tokenizingCharacterSet = [[self class] defaultTokenizingCharacterSet];
[self setBezeled:YES];
[self _init];
[self setObjectValue:[]];
[self setNeedsLayout];
}
return self;
}
- (void)_init
{
_selectedRange = CPMakeRange(0, 0);
var frame = [self frame];
_tokenScrollView = [[CPScrollView alloc] initWithFrame:CGRectMakeZero()];
[_tokenScrollView setHasHorizontalScroller:NO];
[_tokenScrollView setHasVerticalScroller:NO];
[_tokenScrollView setAutoresizingMask:CPViewWidthSizable | CPViewHeightSizable];
var contentView = [[CPView alloc] initWithFrame:CGRectMakeZero()];
[contentView setAutoresizingMask:CPViewWidthSizable];
[_tokenScrollView setDocumentView:contentView];
[self addSubview:_tokenScrollView];
}
- (_CPAutocompleteMenu)_autocompleteMenu
{
if (!_autocompleteMenu)
_autocompleteMenu = [[_CPAutocompleteMenu alloc] initWithTextField:self];
return _autocompleteMenu;
}
- (void)_autocompleteWithDOMEvent:(JSObject)DOMEvent
{
if (![self _inputElement].value && (![_autocompleteMenu contentArray] || ![self hasThemeState:CPThemeStateAutocompleting]))
return;
[self _hideCompletions];
var token = [_autocompleteMenu selectedItem],
shouldRemoveLastObject = token !== @"" && [self _inputElement].value !== @"";
if (!token)
token = [self _inputElement].value;
// Make sure the user typed an actual token to prevent the previous token from being emptied
// If the input area is empty, we want to fall back to the normal behavior, resigning first
// responder or selecting the next or previous key view.
if (!token || token === @"")
{
if (DOMEvent && DOMEvent.keyCode === CPTabKeyCode)
{
if (!DOMEvent.shiftKey)
[[self window] selectNextKeyView:self];
else
[[self window] selectPreviousKeyView:self];
}
else
[[self window] makeFirstResponder:nil];
return;
}
var objectValue = [self objectValue];
// Remove the uncompleted token and add the token string.
// Explicitly remove the last object because the array contains strings and removeObject uses isEqual to compare objects
if (shouldRemoveLastObject)
[objectValue removeObjectAtIndex:_selectedRange.location];
// Convert typed text into a represented object.
token = [self _representedObjectForEditingString:token];
// Give the delegate a chance to confirm, replace or add to the list of tokens being added.
var delegateApprovedObjects = [self _shouldAddObjects:[CPArray arrayWithObject:token] atIndex:_selectedRange.location],
delegateApprovedObjectsCount = [delegateApprovedObjects count];
if (delegateApprovedObjects)
{
for (var i = 0; i < delegateApprovedObjectsCount; i++)
{
[objectValue insertObject:[delegateApprovedObjects objectAtIndex:i] atIndex:_selectedRange.location + i];
}
}
// Put the cursor after the last inserted token.
var location = _selectedRange.location;
[self setObjectValue:objectValue];
if (delegateApprovedObjectsCount)
location += delegateApprovedObjectsCount;
_selectedRange = CPMakeRange(location, 0);
[self _inputElement].value = @"";
[self setNeedsLayout];
[self _controlTextDidChange];
}
- (void)_autocomplete
{
[self _autocompleteWithDOMEvent:nil];
}
- (void)_selectToken:(_CPTokenFieldToken)token byExtendingSelection:(BOOL)extend
{
var indexOfToken = [[self _tokens] indexOfObject:token];
if (indexOfToken == CPNotFound)
{
if (!extend)
_selectedRange = CPMakeRange([[self _tokens] count], 0);
}
else if (extend)
_selectedRange = CPUnionRange(_selectedRange, CPMakeRange(indexOfToken, 1));
else
_selectedRange = CPMakeRange(indexOfToken, 1);
[self setNeedsLayout];
}
- (void)_deselectToken:(_CPTokenFieldToken)token
{
var indexOfToken = [[self _tokens] indexOfObject:token];
if (CPLocationInRange(indexOfToken, _selectedRange))
_selectedRange = CPMakeRange(MAX(indexOfToken, _selectedRange.location), MIN(_selectedRange.length, indexOfToken - _selectedRange.location));
[self setNeedsLayout];
}
- (void)_deleteToken:(_CPTokenFieldToken)token
{
var indexOfToken = [[self _tokens] indexOfObject:token],
objectValue = [self objectValue];
// If the selection was to the right of the deleted token, move it to the left. If the deleted token was
// selected, deselect it.
if (indexOfToken < _selectedRange.location)
_selectedRange.location--;
else
[self _deselectToken:token];
// Preserve selection.
var selection = CPCopyRange(_selectedRange);
[objectValue removeObjectAtIndex:indexOfToken];
[self setObjectValue:objectValue];
_selectedRange = selection;
[self setNeedsLayout];
[self _controlTextDidChange];
}
- (void)_controlTextDidChange
{
var binderClass = [[self class] _binderClassForBinding:CPValueBinding],
theBinding = [binderClass getBinding:CPValueBinding forObject:self];
if (theBinding)
[theBinding reverseSetValueFor:@"objectValue"];
[self textDidChange:[CPNotification notificationWithName:CPControlTextDidChangeNotification object:self userInfo:nil]];
_shouldNotifyTarget = YES;
}
- (void)_removeSelectedTokens:(id)sender
{
var tokens = [self objectValue];
for (var i = _selectedRange.length - 1; i >= 0; i--)
[tokens removeObjectAtIndex:_selectedRange.location + i];
var collapsedSelection = _selectedRange.location;
[self setObjectValue:tokens];
// setObjectValue moves the cursor to the end of the selection. We want it to stay
// where the selected tokens were.
_selectedRange = CPMakeRange(collapsedSelection, 0);
[self _controlTextDidChange];
}
- (void)_updatePlaceholderState
{
if (([[self _tokens] count] === 0) && ![self hasThemeState:CPThemeStateEditing])
[self setThemeState:CPTextFieldStatePlaceholder];
else
[self unsetThemeState:CPTextFieldStatePlaceholder];
}
// =============
// = RESPONDER =
// =============
- (BOOL)becomeFirstResponder
{
if (CPTokenFieldInputOwner && [CPTokenFieldInputOwner window] !== [self window])
[[CPTokenFieldInputOwner window] makeFirstResponder:nil];
[self setThemeState:CPThemeStateEditing];
[self _updatePlaceholderState];
[self setNeedsLayout];
#if PLATFORM(DOM)
var string = [self stringValue],
element = [self _inputElement];
element.value = nil;
element.style.color = [[self currentValueForThemeAttribute:@"text-color"] cssString];
element.style.font = [[self currentValueForThemeAttribute:@"font"] cssString];
element.style.zIndex = 1000;
switch ([self alignment])
{
case CPCenterTextAlignment: element.style.textAlign = "center";
break;
case CPRightTextAlignment: element.style.textAlign = "right";
break;
default: element.style.textAlign = "left";
}
var contentRect = [self contentRectForBounds:[self bounds]];
element.style.top = CGRectGetMinY(contentRect) + "px";
element.style.left = (CGRectGetMinX(contentRect) - 1) + "px"; // why -1?
element.style.width = CGRectGetWidth(contentRect) + "px";
element.style.height = CGRectGetHeight(contentRect) + "px";
[_tokenScrollView documentView]._DOMElement.appendChild(element);
window.setTimeout(function()
{
element.focus();
CPTokenFieldInputOwner = self;
}, 0.0);
//post CPControlTextDidBeginEditingNotification
[self textDidBeginEditing:[CPNotification notificationWithName:CPControlTextDidBeginEditingNotification object:self userInfo:nil]];
[[[self window] platformWindow] _propagateCurrentDOMEvent:YES];
CPTokenFieldInputIsActive = YES;
if (document.attachEvent)
{
CPTokenFieldCachedSelectStartFunction = document.body.onselectstart;
CPTokenFieldCachedDragFunction = document.body.ondrag;
document.body.ondrag = function () {};
document.body.onselectstart = function () {};
}
#endif
return YES;
}
- (BOOL)resignFirstResponder
{
if (_preventResign)
return NO;
[self unsetThemeState:CPThemeStateEditing];
[self _autocomplete];
#if PLATFORM(DOM)
var element = [self _inputElement];
CPTokenFieldInputResigning = YES;
element.blur();
if (!CPTokenFieldInputDidBlur)
CPTokenFieldBlurFunction();
CPTokenFieldInputDidBlur = NO;
CPTokenFieldInputResigning = NO;
if (element.parentNode == [_tokenScrollView documentView]._DOMElement)
element.parentNode.removeChild(element);
CPTokenFieldInputIsActive = NO;
if (document.attachEvent)
{
CPTokenFieldCachedSelectStartFunction = nil;
CPTokenFieldCachedDragFunction = nil;
document.body.ondrag = CPTokenFieldCachedDragFunction
document.body.onselectstart = CPTokenFieldCachedSelectStartFunction
}
#endif
[self _updatePlaceholderState];
[self setNeedsLayout];
if (_shouldNotifyTarget)
{
_shouldNotifyTarget = NO;
[self textDidEndEditing:[CPNotification notificationWithName:CPControlTextDidEndEditingNotification object:self userInfo:nil]];
if ([self sendsActionOnEndEditing])
[self sendAction:[self action] to:[self target]];
}
return YES;
}
- (void)mouseDown:(CPEvent)anEvent
{
_preventResign = YES;
_mouseDownEvent = anEvent;
[self _selectToken:nil byExtendingSelection:NO];
[super mouseDown:anEvent];
}
- (void)mouseUp:(CPEvent)anEvent
{
_preventResign = NO;
_mouseDownEvent = nil;
}
- (void)mouseDownOnToken:(_CPTokenFieldToken)aToken withEvent:(CPEvent)anEvent
{
_preventResign = YES;
_mouseDownEvent = anEvent;
}
- (void)mouseUpOnToken:(_CPTokenFieldToken)aToken withEvent:(CPEvent)anEvent
{
if (_mouseDownEvent && CGPointEqualToPoint([_mouseDownEvent locationInWindow], [anEvent locationInWindow]))
{
[self _selectToken:aToken byExtendingSelection:[anEvent modifierFlags] & CPShiftKeyMask];
[[self window] makeFirstResponder:self];
// Snap to the token if it's only half visible due to mouse wheel scrolling.
_shouldScrollTo = aToken;
}
_preventResign = NO;
}
// ===========
// = CONTROL =
// ===========
- (CPArray)_tokens
{
// We return super here because objectValue uses this method
// If we called self we would loop infinitely
return [super objectValue];
}
- (CPString)stringValue
{
return [[self objectValue] componentsJoinedByString:@","];
}
- (id)objectValue
{
var objectValue = [];
for (var i = 0, count = [[self _tokens] count]; i < count; i++)
{
var token = [[self _tokens] objectAtIndex:i];
if ([token isKindOfClass:[CPString class]])
continue;
[objectValue addObject:[token representedObject]];
}
#if PLATFORM(DOM)
if ([self _inputElement].value != @"")
[objectValue insertObject:[self _inputElement].value atIndex:_selectedRange.location];
#endif
return objectValue;
}
- (void)setObjectValue:(id)aValue
{
if (aValue !== nil && ![aValue isKindOfClass:[CPArray class]])
{
[super setObjectValue:nil];
return;
}
var superValue = [super objectValue];
if (aValue === superValue || [aValue isEqualToArray:superValue])
return;
var contentView = [_tokenScrollView documentView];
// Preserve as many existing tokens as possible to reduce redraw flickering.
var oldTokens = [self _tokens],
newTokens = [];
if (aValue !== nil)
{
for (var i = 0, count = [aValue count]; i < count; i++)
{
// Do we have this token among the old ones?
var tokenObject = aValue[i],
tokenValue = [self _displayStringForRepresentedObject:tokenObject],
newToken = nil;
for (var j = 0, oldCount = [oldTokens count]; j < oldCount; j++)
{
var oldToken = oldTokens[j];
if ([oldToken representedObject] == tokenObject)
{
// Yep. Reuse it.
[oldTokens removeObjectAtIndex:j];
newToken = oldToken;
break;
}
}
if (newToken === nil)
{
newToken = [[_CPTokenFieldToken alloc] init];
[newToken setTokenField:self];
[newToken setRepresentedObject:tokenObject];
[newToken setStringValue:tokenValue];
[contentView addSubview:newToken];
}
newTokens.push(newToken);
}
}
// Remove any now unused tokens.
for (var j = 0, oldCount = [oldTokens count]; j < oldCount; j++)
[oldTokens[j] removeFromSuperview];
/*
[CPTextField setObjectValue] will try to set the _inputElement.value to
the new objectValue, if the _inputElement exists. This is wrong for us
since our objectValue is an array of tokens, so we can't use
[super setObjectValue:objectValue];
Instead do what CPControl setObjectValue would.
*/
_value = newTokens;
// Reset the selection.
[self _selectToken:nil byExtendingSelection:NO];
[self _updatePlaceholderState];
_shouldScrollTo = CPScrollDestinationRight;
[self setNeedsLayout];
[self setNeedsDisplay:YES];
}
- (void)sendAction:(SEL)anAction to:(id)anObject
{
_shouldNotifyTarget = NO;
[super sendAction:anAction to:anObject];
}
// Incredible hack to disable supers implementation
// so it cannot change our object value and break the tokenfield
- (void)_setStringValue:(id)aValue
{
}
// =============
// = TEXTFIELD =
// =============
#if PLATFORM(DOM)
- (DOMElement)_inputElement
{
if (!CPTokenFieldDOMInputElement)
{
CPTokenFieldDOMInputElement = document.createElement("input");
CPTokenFieldDOMInputElement.style.position = "absolute";
CPTokenFieldDOMInputElement.style.border = "0px";
CPTokenFieldDOMInputElement.style.padding = "0px";
CPTokenFieldDOMInputElement.style.margin = "0px";
CPTokenFieldDOMInputElement.style.whiteSpace = "pre";
CPTokenFieldDOMInputElement.style.background = "transparent";
CPTokenFieldDOMInputElement.style.outline = "none";
CPTokenFieldBlurFunction = function(anEvent)
{
if (CPTokenFieldInputOwner && [CPTokenFieldInputOwner._tokenScrollView documentView]._DOMElement != CPTokenFieldDOMInputElement.parentNode)
return;
if (CPTokenFieldInputOwner && CPTokenFieldInputOwner._preventResign)
return false;
if (!CPTokenFieldInputResigning && !CPTokenFieldFocusInput)
{
[[CPTokenFieldInputOwner window] makeFirstResponder:nil];
return;
}
CPTokenFieldHandleBlur(anEvent, CPTokenFieldDOMInputElement);
CPTokenFieldInputDidBlur = YES;
return true;
};
CPTokenFieldKeyDownFunction = function(aDOMEvent)
{
aDOMEvent = aDOMEvent || window.event;
CPTokenFieldTextDidChangeValue = [CPTokenFieldInputOwner stringValue];
if (aDOMEvent.keyCode === CPUpArrowKeyCode)
[[CPTokenFieldInputOwner _autocompleteMenu] selectPrevious];
else if (aDOMEvent.keyCode === CPDownArrowKeyCode)
[[CPTokenFieldInputOwner _autocompleteMenu] selectNext];
var owner = CPTokenFieldInputOwner;
if (aDOMEvent.keyCode === CPReturnKeyCode || aDOMEvent.keyCode === CPTabKeyCode)
{
if (aDOMEvent.preventDefault)
aDOMEvent.preventDefault();
if (aDOMEvent.stopPropagation)
aDOMEvent.stopPropagation();
aDOMEvent.cancelBubble = true;
// Only resign first responder if we weren't auto-completing
if (![CPTokenFieldInputOwner hasThemeState:CPThemeStateAutocompleting])
{
if (aDOMEvent && aDOMEvent.keyCode === CPReturnKeyCode)
{
[owner sendAction:[owner action] to:[owner target]];
[[owner window] makeFirstResponder:nil];
}
else if (aDOMEvent && aDOMEvent.keyCode === CPTabKeyCode)
{
if (!aDOMEvent.shiftKey)
[[owner window] selectNextKeyView:owner];
else
[[owner window] selectPreviousKeyView:owner];
}
}
[owner _autocompleteWithDOMEvent:aDOMEvent];
[owner setNeedsLayout];
}
else if (aDOMEvent.keyCode === CPEscapeKeyCode)
{
[CPTokenFieldInputOwner _hideCompletions];
}
else if (aDOMEvent.keyCode === CPUpArrowKeyCode || aDOMEvent.keyCode === CPDownArrowKeyCode)
{
if (aDOMEvent.preventDefault)
aDOMEvent.preventDefault();
if (aDOMEvent.stopPropagation)
aDOMEvent.stopPropagation();
aDOMEvent.cancelBubble = true;
}
else if (aDOMEvent.keyCode == CPLeftArrowKeyCode && owner._selectedRange.location > 0 && CPTokenFieldDOMInputElement.value == "")
{
// Move the cursor back one token if the input is empty and the left arrow key is pressed.
if (!aDOMEvent.shiftKey)
{
if (owner._selectedRange.length)
// Simply collapse the range.
owner._selectedRange.length = 0;
else
owner._selectedRange.location--;
}
else
{
owner._selectedRange.location--;
// When shift is depressed, select the next token backwards.
owner._selectedRange.length++;
}
owner._shouldScrollTo = CPScrollDestinationLeft;
[owner setNeedsLayout];
}
else if (aDOMEvent.keyCode == CPRightArrowKeyCode && owner._selectedRange.location < [[owner _tokens] count] && CPTokenFieldDOMInputElement.value == "")
{
if (!aDOMEvent.shiftKey)
{
if (owner._selectedRange.length)
{
// Place the cursor at the end of the selection and collapse.
owner._selectedRange.location = CPMaxRange(owner._selectedRange);
owner._selectedRange.length = 0;
}
else
{
// Move the cursor forward one token if the input is empty and the right arrow key is pressed.
owner._selectedRange.location = MIN([[owner _tokens] count], owner._selectedRange.location + owner._selectedRange.length + 1);
}
}
else
{
// Leave the selection location in place but include the next token to the right.
owner._selectedRange.length++;
}
owner._shouldScrollTo = CPScrollDestinationRight;
[owner setNeedsLayout];
}
else if (aDOMEvent.keyCode === CPDeleteKeyCode)
{
// Highlight the previous token if backspace was pressed in an empty input element or re-show the completions view
if (CPTokenFieldDOMInputElement.value == @"")
{
[self _hideCompletions];
if (CPEmptyRange(CPTokenFieldInputOwner._selectedRange))
{
if (CPTokenFieldInputOwner._selectedRange.location > 0)
{
var tokens = [CPTokenFieldInputOwner _tokens],
tokenView = [tokens objectAtIndex:(CPTokenFieldInputOwner._selectedRange.location - 1)];
[CPTokenFieldInputOwner _selectToken:tokenView byExtendingSelection:NO];
}
}
else
[CPTokenFieldInputOwner _removeSelectedTokens:nil];
}
else
[CPTokenFieldInputOwner _delayedShowCompletions];
}
else if (aDOMEvent.keyCode === CPDeleteForwardKeyCode && CPTokenFieldDOMInputElement.value == @"")
{
// Delete forward if nothing is selected, else delete all selected.
[self _hideCompletions];
if (CPEmptyRange(CPTokenFieldInputOwner._selectedRange))
{
var tokens = [CPTokenFieldInputOwner _tokens];
if (CPTokenFieldInputOwner._selectedRange.location < [tokens count])
[CPTokenFieldInputOwner _deleteToken:tokens[CPTokenFieldInputOwner._selectedRange.location]];
}
else
[CPTokenFieldInputOwner _removeSelectedTokens:nil];
}
return true;
};
CPTokenFieldKeyPressFunction = function(aDOMEvent)
{
aDOMEvent = aDOMEvent || window.event;
var character = String.fromCharCode(aDOMEvent.keyCode || aDOMEvent.which),
owner = CPTokenFieldInputOwner;
if ([[owner tokenizingCharacterSet] characterIsMember:character])
{
if (aDOMEvent.preventDefault)
aDOMEvent.preventDefault();
if (aDOMEvent.stopPropagation)
aDOMEvent.stopPropagation();
aDOMEvent.cancelBubble = true;
[owner _autocompleteWithDOMEvent:aDOMEvent];
[owner setNeedsLayout];
return true;
}
[CPTokenFieldInputOwner _delayedShowCompletions];
// If there was a selection, collapse it now since we're typing in a new token.
owner._selectedRange.length = 0;
// Force immediate layout in case word wrapping is now necessary.
[owner setNeedsLayout];
[[CPRunLoop currentRunLoop] limitDateForMode:CPDefaultRunLoopMode];
};
CPTokenFieldKeyUpFunction = function()
{
if ([CPTokenFieldInputOwner stringValue] !== CPTokenFieldTextDidChangeValue)
{
CPTokenFieldTextDidChangeValue = [CPTokenFieldInputOwner stringValue];
[CPTokenFieldInputOwner textDidChange:[CPNotification notificationWithName:CPControlTextDidChangeNotification object:CPTokenFieldInputOwner userInfo:nil]];
}
[self setNeedsLayout];
[[CPRunLoop currentRunLoop] limitDateForMode:CPDefaultRunLoopMode];
};
CPTokenFieldHandleBlur = function(anEvent)
{
CPTokenFieldInputOwner = nil;
[[CPRunLoop currentRunLoop] limitDateForMode:CPDefaultRunLoopMode];
};
if (document.attachEvent)
{
CPTokenFieldDOMInputElement.attachEvent("on" + CPDOMEventKeyUp, CPTokenFieldKeyUpFunction);
CPTokenFieldDOMInputElement.attachEvent("on" + CPDOMEventKeyDown, CPTokenFieldKeyDownFunction);
CPTokenFieldDOMInputElement.attachEvent("on" + CPDOMEventKeyPress, CPTokenFieldKeyPressFunction);
}
else
{
CPTokenFieldDOMInputElement.addEventListener(CPDOMEventKeyUp, CPTokenFieldKeyUpFunction, NO);
CPTokenFieldDOMInputElement.addEventListener(CPDOMEventKeyDown, CPTokenFieldKeyDownFunction, NO);
CPTokenFieldDOMInputElement.addEventListener(CPDOMEventKeyPress, CPTokenFieldKeyPressFunction, NO);
}
//FIXME make this not onblur
CPTokenFieldDOMInputElement.onblur = CPTokenFieldBlurFunction;
CPTokenFieldDOMStandardInputElement = CPTokenFieldDOMInputElement;
}
if (CPFeatureIsCompatible(CPInputTypeCanBeChangedFeature))
{
if ([CPTokenFieldInputOwner isSecure])
CPTokenFieldDOMInputElement.type = "password";
else
CPTokenFieldDOMInputElement.type = "text";
return CPTokenFieldDOMInputElement;
}
return CPTokenFieldDOMInputElement;
}
#endif
// - (void)setTokenStyle: (NSTokenStyle) style;
// - (NSTokenStyle)tokenStyle;
//
// ====================
// = COMPLETION DELAY =
// ====================
- (void)setCompletionDelay:(CPTimeInterval)delay
{
_completionDelay = delay;
}
- (NSTimeInterval)completionDelay
{
return _completionDelay;
}
+ (NSTimeInterval)defaultCompletionDelay
{
return 0.5;
}
// ==========
// = LAYOUT =
// ==========
- (void)layoutSubviews
{
[super layoutSubviews];
[_tokenScrollView setFrame:[self rectForEphemeralSubviewNamed:"content-view"]];
var textFieldContentView = [self layoutEphemeralSubviewNamed:@"content-view"
positioned:CPWindowAbove
relativeToEphemeralSubviewNamed:@"bezel-view"];
if (textFieldContentView)
[textFieldContentView setHidden:[self stringValue] !== @""];
var frame = [self frame],
contentView = [_tokenScrollView documentView],
tokens = [self _tokens],
shouldShowAutoComplete = [self hasThemeState:CPThemeStateAutocompleting];
// Hack to make sure we are handling an array
if (![tokens isKindOfClass:[CPArray class]])
return;
// Move each token into the right position.
var contentRect = CGRectMakeCopy([contentView bounds]),
contentOrigin = contentRect.origin,
contentSize = contentRect.size,
offset = CPPointMake(contentOrigin.x, contentOrigin.y),
spaceBetweenTokens = CPSizeMake(2.0, 2.0),
isEditing = [[self window] firstResponder] == self,
tokenToken = [_CPTokenFieldToken new];
// Get the height of a typical token, or a token token if you will.
[tokenToken sizeToFit];
var tokenHeight = CGRectGetHeight([tokenToken bounds]);
var fitAndFrame = function(width, height)
{
var r = CGRectMake(0, 0, width, height);
if (offset.x + width >= contentSize.width && offset.x > contentOrigin.x)
{
offset.x = contentOrigin.x;
offset.y += height + spaceBetweenTokens.height;
}
r.origin.x = offset.x;
r.origin.y = offset.y;
// Make sure the frame fits.
if (CGRectGetHeight([contentView bounds]) < offset.y + height)
[contentView setFrame:CGRectMake(0, 0, CGRectGetWidth([_tokenScrollView bounds]), offset.y + height)];
offset.x += width + spaceBetweenTokens.width;
return r;
};
var placeEditor = function(useRemainingWidth)
{
var element = [self _inputElement],
textWidth = 1;
if (_selectedRange.length === 0)
{
// XXX The "X" here is used to estimate the space needed to fit the next character
// without clipping. Since different fonts might have different sizes of "X" this
// solution is not ideal, but it works.
textWidth = [(element.value || @"") + "X" sizeWithFont:[self font]].width;
if (useRemainingWidth)
textWidth = MAX(contentSize.width - offset.x - 1, textWidth);
}
var inputFrame = fitAndFrame(textWidth, tokenHeight);
element.style.left = inputFrame.origin.x + "px";
element.style.top = inputFrame.origin.y + "px";
element.style.width = inputFrame.size.width + "px";
element.style.height = inputFrame.size.height + "px";
// When editing, always scroll to the cursor.
if (_selectedRange.length == 0)
[[_tokenScrollView documentView] scrollRectToVisible:inputFrame];
};
for (var i = 0, count = [tokens count]; i < count; i++)
{
if (isEditing && i == CPMaxRange(_selectedRange))
placeEditor(false);
var tokenView = [tokens objectAtIndex:i];
// Make sure we are only changing completed tokens
if ([tokenView isKindOfClass:[CPString class]])
continue;
[tokenView setHighlighted:CPLocationInRange(i, _selectedRange)];
[tokenView sizeToFit];
var size = [contentView bounds].size,
tokenViewSize = [tokenView bounds].size,
tokenFrame = fitAndFrame(tokenViewSize.width, tokenViewSize.height);
[tokenView setFrame:tokenFrame];
}
if (isEditing && CPMaxRange(_selectedRange) >= [tokens count])
placeEditor(true);
// Hide the editor if there are selected tokens, but still keep it active
// so we can continue using our standard keyboard handling events.
if (isEditing && _selectedRange.length)
{
[self _inputElement].style.left = "-10000px";
[self _inputElement].focus();
}
// Trim off any excess height downwards.
if (CGRectGetHeight([contentView bounds]) > offset.y + tokenHeight)
[contentView setFrame:CGRectMake(0, 0, CGRectGetWidth([_tokenScrollView bounds]), offset.y + tokenHeight)];
if (_shouldScrollTo !== CPScrollDestinationNone)
{
// Only carry out the scroll if the cursor isn't visible.
if (!(isEditing && _selectedRange.length == 0))
{
var scrollToToken = _shouldScrollTo;
if (scrollToToken === CPScrollDestinationLeft)
scrollToToken = tokens[_selectedRange.location]
else if (scrollToToken === CPScrollDestinationRight)
scrollToToken = tokens[MAX(0, CPMaxRange(_selectedRange) - 1)];
[self _scrollTokenViewToVisible:scrollToToken];
}
_shouldScrollTo = CPScrollDestinationNone;
}
}
- (BOOL)_scrollTokenViewToVisible:(_CPTokenFieldToken)aToken
{
if (!aToken)
return;
return [[_tokenScrollView documentView] scrollRectToVisible:[aToken frame]];
}