-
Notifications
You must be signed in to change notification settings - Fork 6
/
TSStackView.m
704 lines (557 loc) · 20.1 KB
/
TSStackView.m
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
//
// TSStackView.m
// BrightPay
//
// Created by Jonathan Mitchell on 04/12/2013.
// Copyright (c) 2013 Thesaurus Software Limited. All rights reserved.
//
#import "TSStackView.h"
#import "TSClipView.h"
#define TS_LOG_SUBTREE
#undef TS_LOG_SUBTREE // comment this to log the subtree
@interface NSView (TSStackView)
+ (void)ts_disableTranslatesAutoresizingMaskIntoConstraints:(NSArray *)views;
- (void)ts_disableTranslatesAutoresizingMaskIntoConstraints:(NSArray *)views;
@end
char BPContextHidden;
@interface TSStackView ()
// collections
@property (strong) NSMutableDictionary *observedViews;
@property (strong) NSArray *stackViewConstraints;
@property (strong) NSMutableArray *pendingVisibleViews;
@property (strong) NSMutableArray *pendingHiddenViews;
// objects
@property (strong) NSLayoutConstraint *autoContentHeightConstraint;
@property (strong) NSLayoutConstraint *autoContentWidthConstraint;
// primitives
@property (assign) BOOL scrollViewAllocated;
@property BOOL doLayout;
@end
@implementation TSStackView
#pragma mark -
#pragma mark Factory
+ (id)stackViewWithViews:(NSArray *)views
{
return [self stackViewWithViews:views inGravity:NSStackViewGravityLeading];
}
+ (id)stackViewWithViews:(NSArray *)views inGravity:(NSStackViewGravity)gravity
{
views = [self flattenViews:views];
// the super call apparently guarantees that self.translatesAutoresizingMaskIntoConstraints == NO
[self ts_disableTranslatesAutoresizingMaskIntoConstraints:views];
NSArray *leadingViews = nil;
if (gravity == NSStackViewGravityLeading) {
leadingViews = views;
views = nil;
}
TSStackView *stackView = [super stackViewWithViews:leadingViews];
if (views) {
[stackView addViews:views inGravity:gravity];
}
return stackView;
}
#pragma mark -
#pragma mark Flat stuff
+ (NSArray *)flattenViews:(NSArray *)views
{
NSMutableArray *flatViews = [NSMutableArray arrayWithCapacity:[views count]];
for (id object in views) {
if ([object isKindOfClass:[NSView class]]) {
[flatViews addObject:object];
} else if ([object isKindOfClass:[NSArray class]]) {
[flatViews addObjectsFromArray:[self flattenViews:object]];
} else {
NSLog(@"Cannot flatten this : %@", object);
}
}
return flatViews;
}
#pragma mark -
#pragma mark Setup
- (id)initWithFrame:(NSRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[self setup];
}
return self;
}
- (id)initWithCoder:(NSCoder *)aCoder
{
self = [super initWithCoder:aCoder];
if (self) {
[self setup];
}
return self;
}
- (void)setup
{
_observedViews = [NSMutableDictionary new];
_doLayout = YES;
_pendingVisibleViews = [NSMutableArray arrayWithCapacity:3];
_pendingHiddenViews = [NSMutableArray arrayWithCapacity:3];
self.wantsLayer = YES;
if (self.class.awakeBlock) {
self.class.awakeBlock(self);
}
self.clipsToBounds = YES;
}
static void(^m_awakeBlock)(TSStackView *);
+ (void)setAwakeBlock:(void (^)(TSStackView *))awakeBlock
{
m_awakeBlock = awakeBlock;
}
+ (void (^)(TSStackView *))awakeBlock
{
return m_awakeBlock;
}
#pragma mark -
#pragma mark Teardown
- (void)dealloc
{
[self removeAllViewObservations];
}
#pragma mark -
#pragma mark Visible views
- (void)setVisibleViews:(NSArray *)views inGravity:(NSStackViewGravity)gravity
{
// Extract the visible items
NSMutableArray *visibleViews = [NSMutableArray arrayWithCapacity:[views count]];
for (NSView *view in views) {
if (!view.isHidden) [visibleViews addObject:view];
}
[super setViews:visibleViews inGravity:gravity];
// call block on views pending visibility change
for (NSView *view in views) {
if (!view.hidden) {
if ([self.pendingVisibleViews containsObject:view]) {
[self.pendingVisibleViews removeObject:view];
// bound view has become visible
if (self.onBoundViewVisible) {
self.onBoundViewVisible(self, view);
}
}
}
else {
if ([self.pendingHiddenViews containsObject:view]) {
[self.pendingHiddenViews removeObject:view];
// bound view has been hidden
if (self.onBoundViewHidden) {
self.onBoundViewHidden(self, view);
}
}
}
}
[self invalidateContentSize];
}
#pragma mark -
#pragma mark Observed views
- (void)setObservedViews:(NSArray *)views inGravity:(NSStackViewGravity)gravity
{
[self removeViewObservations:[self observedViewsInGravity:gravity]];
self.observedViews[@(gravity)] = [NSMutableArray arrayWithArray:views];
[self addViewObservations:[self observedViewsInGravity:gravity]];
}
- (NSArray *)observedViewsInGravity:(NSStackViewGravity)gravity
{
return self.observedViews[@(gravity)];
}
- (NSArray *)allViewsInGravity:(NSStackViewGravity)gravity
{
return self.observedViews[@(gravity)];
}
- (NSArray *)allViews
{
NSMutableArray *allViews = [NSMutableArray arrayWithCapacity:3];
for (id i in @[@(NSStackViewGravityTop), @(NSStackViewGravityCenter), @(NSStackViewGravityBottom)]) {
NSArray *views = self.observedViews[i];
if (views) {
[allViews addObjectsFromArray:views];
}
}
return allViews;
}
#pragma mark -
#pragma mark Visibility
- (void)hideViewsInGravity:(NSStackViewGravity)gravity
{
[self hideViews:[self viewsInGravity:gravity]];
}
- (void)showViewsInGravity:(NSStackViewGravity)gravity
{
[self showViews:[self viewsInGravity:gravity]];
}
- (void)showViews:(NSArray *)views
{
for (NSView *view in views) view.hidden = NO;
}
- (void)hideViews:(NSArray *)views
{
for (NSView *view in views) view.hidden = YES;
}
#pragma mark -
#pragma mark Gravity
- (NSStackViewGravity)gravityForObservedView:(NSView *)view
{
for (NSStackViewGravity gravity = NSStackViewGravityTop; gravity <= NSStackViewGravityBottom; gravity++) {
if ([[self observedViewsInGravity:gravity] containsObject:view]) return gravity;
}
return NSNotFound;
}
- (NSStackViewGravity)gravityForView:(NSView *)view
{
for (NSStackViewGravity gravity = NSStackViewGravityTop; gravity <= NSStackViewGravityBottom; gravity++) {
if ([[self viewsInGravity:gravity] containsObject:view]) return gravity;
}
return NSNotFound;
}
#pragma mark -
#pragma mark KVO
- (void)addViewObservation:(NSView *)view
{
[view addObserver:self forKeyPath:@"hidden" options:(NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld) context:&BPContextHidden];
}
- (void)addViewObservations:(NSArray *)views
{
for (NSView *view in views) {
[self addViewObservation:view];
}
}
- (void)removeViewObservation:(NSView *)view
{
[view removeObserver:self forKeyPath:@"hidden" context:&BPContextHidden];
}
- (void)removeViewObservations:(NSArray *)views
{
for (NSView *view in views) {
[self removeViewObservation:view];
}
}
- (void)removeAllViewObservations
{
[self removeViewObservations:self.observedViews[@(NSStackViewGravityTop)]];
[self removeViewObservations:self.observedViews[@(NSStackViewGravityCenter)]];
[self removeViewObservations:self.observedViews[@(NSStackViewGravityBottom)]];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if (context == &BPContextHidden) {
NSView *view = (NSView *)object;
NSAssert([view isKindOfClass:[NSView class]], @"NSView expected");
// track the views transition
BOOL wasHidden = NO;
BOOL isHidden = NO;
if (change[NSKeyValueChangeOldKey]) {
wasHidden = [(NSNumber *)change[NSKeyValueChangeOldKey] boolValue];
}
if (change[NSKeyValueChangeNewKey]) {
isHidden = [(NSNumber *)change[NSKeyValueChangeNewKey] boolValue];
}
if (wasHidden && !isHidden) {
[self.pendingVisibleViews addObject:view];
}
else if (isHidden && !wasHidden) {
[self.pendingHiddenViews addObject:view];
}
if (self.doLayout) {
// get the gravity for the observed view
NSStackViewGravity gravity = [self gravityForObservedView:view];
// show all visible views in the gravity
[self setVisibleViews:[self observedViewsInGravity:gravity] inGravity:gravity];
}
}
}
#pragma mark -
#pragma mark AutoLayout
- (void)suspendAutoLayoutWhenSubviewVisibilityChanges
{
self.doLayout = NO;
}
- (void)resumeAutoLayoutWhenSubviewVisibilityChanges
{
self.doLayout = YES;
for (NSStackViewGravity gravity = NSStackViewGravityTop; gravity <= NSStackViewGravityBottom; gravity++) {
[self setVisibleViews:[self observedViewsInGravity:gravity] inGravity:gravity];
}
}
- (NSSize)intrinsicContentSize
{
/*
This works reasonably well but it is likely better to use - autoContentSizeOptions
*/
CGFloat intrinsicWidth = NSViewNoInstrinsicMetric;
CGFloat intrinsicHeight = NSViewNoInstrinsicMetric;
// This method makes assumptions about how the internal views are laid out.
// The assumptions are reasonable based on the published geometry for NSStackView.
// However, future changes to NSStackView may cause this method to misbehave.
// calculate intrinsic content height.
if (self.intrinsicContentSizeOptions & TSIntrinsicContentSizeHeight) {
intrinsicHeight = 0;
intrinsicHeight += (self.edgeInsets.top + self.edgeInsets.bottom); // inset
for (NSView *view in self.views) {
intrinsicHeight += [view fittingSize].height;
// spacing
if (view != self.views.lastObject) {
CGFloat viewSpacing = [self customSpacingAfterView:view];
if (viewSpacing == NSStackViewSpacingUseDefault) {
viewSpacing = self.spacing;
}
intrinsicHeight += viewSpacing;
}
}
}
// calculate intrinsic content width
if (self.intrinsicContentSizeOptions & TSIntrinsicContentSizeWidth) {
intrinsicWidth = 0;
intrinsicWidth += (self.edgeInsets.left + self.edgeInsets.right); // inset
for (NSView *view in self.views) {
intrinsicWidth += [view fittingSize].width;
// spacing
if (view != self.views.lastObject) {
CGFloat viewSpacing = [self customSpacingAfterView:view];
if (viewSpacing == NSStackViewSpacingUseDefault) {
viewSpacing = self.spacing;
}
intrinsicWidth += viewSpacing;
}
}
}
#ifdef TS_LOG_SUBTREE
if (self.intrinsicContentSizeOptions != TSIntrinsicContentSizeNone) {
NSLog(@"%@ _subtreeDescription = %@", self, [self performSelector:@selector(_subtreeDescription)]);
}
#endif
return NSMakeSize(intrinsicWidth, intrinsicHeight);
}
#pragma mark -
#pragma mark Auto content size
- (void)updateAutoContentSizeConstraints
{
[self removeConstraint:self.autoContentHeightConstraint];
[self removeConstraint:self.autoContentWidthConstraint];
NSView *lastView = [self.views lastObject];
if (!lastView) {
return;
}
/*
We constrain to self here.
This generally works but problems can arise if we try and use edge insets too.
*/
NSView *stackViewContainer = self;
/*
Constrain the last subview to the bottom of the view
*/
if (self.autoContentSizeOptions & TSAutoContentSizeHeight) {
self.autoContentHeightConstraint = [NSLayoutConstraint constraintWithItem:lastView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:stackViewContainer attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0];
[self addConstraint:self.autoContentHeightConstraint];
}
/*
Constrain the last subview to the right of the view
*/
if (self.autoContentSizeOptions & TSAutoContentSizeWidth) {
self.autoContentWidthConstraint = [NSLayoutConstraint constraintWithItem:lastView attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:stackViewContainer attribute:NSLayoutAttributeRight multiplier:1.0 constant:0];
[self addConstraint:self.autoContentWidthConstraint];
}
}
- (void)setIntrinsicContentSizeOptions:(TSIntrinsicContentSize)intrinsicSizeOptions
{
_intrinsicContentSizeOptions = intrinsicSizeOptions;
[self invalidateContentSize];
}
- (void)setAutoContentSizeOptions:(TSAutoContentSize)autoContentSizeOptions
{
_autoContentSizeOptions = autoContentSizeOptions;
[self updateAutoContentSizeConstraints];
}
- (void)invalidateContentSize
{
[self invalidateIntrinsicContentSize];
[self updateAutoContentSizeConstraints];
}
#pragma mark -
#pragma mark Adding and removing views
- (void)setViews:(NSArray *)views inGravity:(NSStackViewGravity)gravity
{
[self ts_disableTranslatesAutoresizingMaskIntoConstraints:views];
[self setObservedViews:views inGravity:gravity];
[self setVisibleViews:views inGravity:gravity];
[self invalidateContentSize];
}
- (void)addView:(NSView *)aView inGravity:(NSStackViewGravity)gravity
{
[self ts_disableTranslatesAutoresizingMaskIntoConstraints:@[aView]];
if (!aView.isHidden) {
// this will call -insertView:atIndex:inGravity:
[super addView:aView inGravity:gravity];
} else {
[self commitView:aView atIndex:NSNotFound inGravity:gravity];
}
}
- (void)addViews:(NSArray *)views inGravity:(NSStackViewGravity)gravity
{
views = [self.class flattenViews:views];
for (NSView *view in views) {
[self addView:view inGravity:gravity];
}
}
- (void)insertView:(NSView *)aView atIndex:(NSUInteger)index inGravity:(NSStackViewGravity)gravity
{
[self ts_disableTranslatesAutoresizingMaskIntoConstraints:@[aView]];
NSUInteger maxIndex = [self viewsInGravity:gravity].count;
if (index > [self viewsInGravity:gravity].count) {
index = maxIndex;
}
if (!aView.isHidden) {
[super insertView:aView atIndex:index inGravity:gravity];
}
[self commitView:aView atIndex:index inGravity:gravity];
}
- (void)commitView:(NSView *)aView atIndex:(NSUInteger)index inGravity:(NSStackViewGravity)gravity
{
NSMutableArray *observedViews = self.observedViews[@(gravity)];
if (!observedViews) {
self.observedViews[@(gravity)] = [NSMutableArray arrayWithCapacity:3];
observedViews = self.observedViews[@(gravity)];
}
NSAssert(![observedViews containsObject:aView], @"View already observed");
// if no index specified then commit view has been added to list of observed gravity views.
// in this case we simply append the view to the list of observed views.
// if the last view in the list is hidden then the commit view will layout after it.
if (index == NSNotFound) {
[observedViews addObject:aView];
}
else {
// the commit view has been inserted at a specified index.
// we will interpret this index relative to the visible views so
// that when inserting the view into the observed views collection we must take account
// of any preceding views that are currently hidden.
NSInteger iVisible = -1;
BOOL success = NO;
for (NSUInteger i = 0; i < observedViews.count; i++) {
NSView *view = observedViews[i];
if (!view.hidden) {
iVisible++;
}
if (index == (NSUInteger)iVisible) {
[observedViews insertObject:aView atIndex:i];
success = YES;
break;
}
}
if (!success) {
[observedViews addObject:aView];
}
}
[self addViewObservation:aView];
[self invalidateContentSize];
}
- (void)removeView:(NSView *)aView
{
BOOL viewRemoved = NO;
for (NSUInteger gravity = NSStackViewGravityTop; gravity <= NSStackViewGravityBottom; gravity++) {
NSMutableArray *observedViews = self.observedViews[@(gravity)];
if ([observedViews containsObject:aView]) {
[self removeViewObservation:aView];
if (!aView.hidden) {
[super removeView:aView];
}
[observedViews removeObject:aView];
viewRemoved = YES;
break;
}
}
if (!viewRemoved) {
NSLog(@"View not found in stack.");
}
[self invalidateContentSize];
}
- (void)removeViews:(NSArray *)views
{
for (NSView *view in views) {
[self removeView:view];
}
}
- (void)removeAllViews
{
for (NSUInteger gravity = NSStackViewGravityTop; gravity <= NSStackViewGravityBottom; gravity++) {
NSArray *views = [self.observedViews[@(gravity)] copy];
[self removeViews:views];
NSAssert([(NSArray *)self.observedViews[@(gravity)] count] == 0, @"observed views should be 0");
}
}
#pragma mark -
#pragma mark Embedding
static void(^m_scrollViewContainerAwakeBlock)(NSScrollView *);
+ (void)setScrollViewContainerAwakeBlock:(void (^)(NSScrollView *))scrollViewContainerAwakeBlock
{
m_scrollViewContainerAwakeBlock = scrollViewContainerAwakeBlock;
}
+ (void (^)(NSScrollView *))scrollViewContainerAwakeBlock
{
return m_scrollViewContainerAwakeBlock;
}
- (NSScrollView *)scrollViewContainer
{
NSScrollView *scrollView = nil;
if (self.scrollViewAllocated) {
scrollView = [self enclosingScrollView];
}
else {
self.scrollViewAllocated = YES;
// allocate scroll view
scrollView = [[NSScrollView alloc] initWithFrame:NSMakeRect(0, 0, 100, 100)];
scrollView.translatesAutoresizingMaskIntoConstraints = NO;
// allocate flipped clip view
TSClipView *clipView = [[TSClipView alloc] initWithFrame:scrollView.contentView.frame];
clipView.clipsToBounds = YES;
scrollView.contentView = clipView;
NSAssert(scrollView.contentView.isFlipped, @"ScrollView contenView must be flipped? Use TSClipView");
// configure the scrollview
scrollView.borderType = NSNoBorder;
scrollView.hasHorizontalScroller = YES;
scrollView.hasVerticalScroller = YES;
scrollView.autohidesScrollers = YES; // has no effect when scrollView.scrollerStyle == NSScrollerStyleOverlay
// stackview is the document
scrollView.documentView = self;
scrollView.clipsToBounds = YES;
// constrain stackview to match dimension of scrollview
NSDictionary *viewsDict = NSDictionaryOfVariableBindings(self);
NSString *vfl = nil;
if (self.orientation == NSUserInterfaceLayoutOrientationVertical) {
vfl = @"H:|-0-[self]-0-|";
} else {
vfl = @"V:|-0-[self]-0-|";
}
self.stackViewConstraints = [NSLayoutConstraint constraintsWithVisualFormat:vfl options:0 metrics:nil views:viewsDict];
[scrollView addConstraints:self.stackViewConstraints];
if (self.class.scrollViewContainerAwakeBlock) {
self.class.scrollViewContainerAwakeBlock(scrollView);
}
}
return scrollView;
}
#pragma mark -
#pragma mark Layer drawing
- (BOOL)wantsUpdateLayer
{
return YES;
}
- (void)updateLayer
{
if (self.backgroundColor) {
self.layer.backgroundColor = self.backgroundColor.CGColor;
}
}
@end
@implementation NSView (TSStackView)
+ (void)ts_disableTranslatesAutoresizingMaskIntoConstraints:(NSArray *)views
{
for (NSView *view in views) {
view.translatesAutoresizingMaskIntoConstraints = NO;
}
}
- (void)ts_disableTranslatesAutoresizingMaskIntoConstraints:(NSArray *)views
{
[[self class] ts_disableTranslatesAutoresizingMaskIntoConstraints:views];
}
@end