FLEXTableViewController.m 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. //
  2. // FLEXTableViewController.m
  3. // FLEX
  4. //
  5. // Created by Tanner on 7/5/19.
  6. // Copyright © 2019 Flipboard. All rights reserved.
  7. //
  8. #import "FLEXTableViewController.h"
  9. #import "FLEXExplorerViewController.h"
  10. #import "FLEXTabsViewController.h"
  11. #import "FLEXScopeCarousel.h"
  12. #import "FLEXTableView.h"
  13. #import "FLEXUtility.h"
  14. #import "UIBarButtonItem+FLEX.h"
  15. #import <objc/runtime.h>
  16. @interface Block : NSObject
  17. - (void)invoke;
  18. @end
  19. CGFloat const kFLEXDebounceInstant = 0.f;
  20. CGFloat const kFLEXDebounceFast = 0.05;
  21. CGFloat const kFLEXDebounceForAsyncSearch = 0.15;
  22. CGFloat const kFLEXDebounceForExpensiveIO = 0.5;
  23. @interface FLEXTableViewController ()
  24. @property (nonatomic) NSTimer *debounceTimer;
  25. @property (nonatomic) BOOL didInitiallyRevealSearchBar;
  26. @property (nonatomic) UITableViewStyle style;
  27. @property (nonatomic, readonly) UIView *tableHeaderViewContainer;
  28. @end
  29. @implementation FLEXTableViewController
  30. @synthesize tableHeaderViewContainer = _tableHeaderViewContainer;
  31. @synthesize automaticallyShowsSearchBarCancelButton = _automaticallyShowsSearchBarCancelButton;
  32. #pragma mark - Initialization
  33. - (id)init {
  34. #if FLEX_AT_LEAST_IOS13_SDK
  35. if (@available(iOS 13.0, *)) {
  36. self = [self initWithStyle:UITableViewStyleInsetGrouped];
  37. } else {
  38. self = [self initWithStyle:UITableViewStyleGrouped];
  39. }
  40. #else
  41. self = [self initWithStyle:UITableViewStyleGrouped];
  42. #endif
  43. return self;
  44. }
  45. - (id)initWithStyle:(UITableViewStyle)style {
  46. self = [super initWithStyle:style];
  47. if (self) {
  48. _searchBarDebounceInterval = kFLEXDebounceFast;
  49. _showSearchBarInitially = YES;
  50. _style = style;
  51. }
  52. return self;
  53. }
  54. #pragma mark - Public
  55. - (FLEXWindow *)window {
  56. return (id)self.view.window;
  57. }
  58. - (void)setShowsSearchBar:(BOOL)showsSearchBar {
  59. if (_showsSearchBar == showsSearchBar) return;
  60. _showsSearchBar = showsSearchBar;
  61. if (showsSearchBar) {
  62. UIViewController *results = self.searchResultsController;
  63. self.searchController = [[UISearchController alloc] initWithSearchResultsController:results];
  64. self.searchController.searchBar.placeholder = @"Filter";
  65. self.searchController.searchResultsUpdater = (id)self;
  66. self.searchController.delegate = (id)self;
  67. self.searchController.dimsBackgroundDuringPresentation = NO;
  68. self.searchController.hidesNavigationBarDuringPresentation = NO;
  69. /// Not necessary in iOS 13; remove this when iOS 13 is the minimum deployment target
  70. self.searchController.searchBar.delegate = self;
  71. self.automaticallyShowsSearchBarCancelButton = YES;
  72. #if FLEX_AT_LEAST_IOS13_SDK
  73. if (@available(iOS 13, *)) {
  74. self.searchController.automaticallyShowsScopeBar = NO;
  75. }
  76. #endif
  77. [self addSearchController:self.searchController];
  78. } else {
  79. // Search already shown and just set to NO, so remove it
  80. [self removeSearchController:self.searchController];
  81. }
  82. }
  83. - (void)setShowsCarousel:(BOOL)showsCarousel {
  84. if (_showsCarousel == showsCarousel) return;
  85. _showsCarousel = showsCarousel;
  86. if (showsCarousel) {
  87. _carousel = ({
  88. __weak __typeof(self) weakSelf = self;
  89. FLEXScopeCarousel *carousel = [FLEXScopeCarousel new];
  90. carousel.selectedIndexChangedAction = ^(NSInteger idx) {
  91. __typeof(self) self = weakSelf;
  92. [self updateSearchResults:self.searchText];
  93. };
  94. // UITableView won't update the header size unless you reset the header view
  95. [carousel registerBlockForDynamicTypeChanges:^(FLEXScopeCarousel *carousel) {
  96. __typeof(self) self = weakSelf;
  97. [self layoutTableHeaderIfNeeded];
  98. }];
  99. carousel;
  100. });
  101. [self addCarousel:_carousel];
  102. } else {
  103. // Carousel already shown and just set to NO, so remove it
  104. [self removeCarousel:_carousel];
  105. }
  106. }
  107. - (NSInteger)selectedScope {
  108. if (self.searchController.searchBar.showsScopeBar) {
  109. return self.searchController.searchBar.selectedScopeButtonIndex;
  110. } else if (self.showsCarousel) {
  111. return self.carousel.selectedIndex;
  112. } else {
  113. return NSNotFound;
  114. }
  115. }
  116. - (void)setSelectedScope:(NSInteger)selectedScope {
  117. if (self.searchController.searchBar.showsScopeBar) {
  118. self.searchController.searchBar.selectedScopeButtonIndex = selectedScope;
  119. } else if (self.showsCarousel) {
  120. self.carousel.selectedIndex = selectedScope;
  121. }
  122. [self updateSearchResults:self.searchText];
  123. }
  124. - (NSString *)searchText {
  125. return self.searchController.searchBar.text;
  126. }
  127. - (BOOL)automaticallyShowsSearchBarCancelButton {
  128. #if FLEX_AT_LEAST_IOS13_SDK
  129. if (@available(iOS 13, *)) {
  130. return self.searchController.automaticallyShowsCancelButton;
  131. }
  132. #endif
  133. return _automaticallyShowsSearchBarCancelButton;
  134. }
  135. - (void)setAutomaticallyShowsSearchBarCancelButton:(BOOL)value {
  136. #if FLEX_AT_LEAST_IOS13_SDK
  137. if (@available(iOS 13, *)) {
  138. self.searchController.automaticallyShowsCancelButton = value;
  139. }
  140. #endif
  141. _automaticallyShowsSearchBarCancelButton = value;
  142. }
  143. - (void)updateSearchResults:(NSString *)newText { }
  144. - (void)onBackgroundQueue:(NSArray *(^)(void))backgroundBlock thenOnMainQueue:(void(^)(NSArray *))mainBlock {
  145. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  146. NSArray *items = backgroundBlock();
  147. dispatch_async(dispatch_get_main_queue(), ^{
  148. mainBlock(items);
  149. });
  150. });
  151. }
  152. - (void)setsShowsShareToolbarItem:(BOOL)showsShareToolbarItem {
  153. _showsShareToolbarItem = showsShareToolbarItem;
  154. if (self.isViewLoaded) {
  155. [self setupToolbarItems];
  156. }
  157. }
  158. #pragma mark - View Controller Lifecycle
  159. - (void)loadView {
  160. self.view = [FLEXTableView style:self.style];
  161. self.tableView.dataSource = self;
  162. self.tableView.delegate = self;
  163. }
  164. - (void)viewDidLoad {
  165. [super viewDidLoad];
  166. self.tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
  167. // Toolbar
  168. self.navigationController.toolbarHidden = NO;
  169. self.navigationController.hidesBarsOnSwipe = YES;
  170. // On iOS 13, the root view controller shows it's search bar no matter what.
  171. // Turning this off avoids some weird flash the navigation bar does when we
  172. // toggle navigationItem.hidesSearchBarWhenScrolling on and off. The flash
  173. // will still happen on subsequent view controllers, but we can at least
  174. // avoid it for the root view controller
  175. if (@available(iOS 13, *)) {
  176. if (self.navigationController.viewControllers.firstObject == self) {
  177. _showSearchBarInitially = NO;
  178. }
  179. }
  180. }
  181. - (void)viewWillAppear:(BOOL)animated {
  182. [super viewWillAppear:animated];
  183. // When going back, make the search bar reappear instead of hiding
  184. if (@available(iOS 11.0, *)) {
  185. if ((self.pinSearchBar || self.showSearchBarInitially) && !self.didInitiallyRevealSearchBar) {
  186. self.navigationItem.hidesSearchBarWhenScrolling = NO;
  187. }
  188. }
  189. [self setupToolbarItems];
  190. }
  191. - (void)viewDidAppear:(BOOL)animated {
  192. [super viewDidAppear:animated];
  193. // Allow scrolling to collapse the search bar, only if we don't want it pinned
  194. if (@available(iOS 11.0, *)) {
  195. if (self.showSearchBarInitially && !self.pinSearchBar && !self.didInitiallyRevealSearchBar) {
  196. // All this mumbo jumbo is necessary to work around a bug in iOS 13 up to 13.2
  197. // wherein quickly toggling navigationItem.hidesSearchBarWhenScrolling to make
  198. // the search bar appear initially results in a bugged search bar that
  199. // becomes transparent and floats over the screen as you scroll
  200. [UIView animateWithDuration:0.2 animations:^{
  201. self.navigationItem.hidesSearchBarWhenScrolling = YES;
  202. [self.navigationController.view setNeedsLayout];
  203. [self.navigationController.view layoutIfNeeded];
  204. }];
  205. }
  206. }
  207. // We only want to reveal the search bar when the view controller first appears.
  208. self.didInitiallyRevealSearchBar = YES;
  209. }
  210. - (void)willMoveToParentViewController:(UIViewController *)parent {
  211. [super willMoveToParentViewController:parent];
  212. // Reset this since we are re-appearing under a new
  213. // parent view controller and need to show it again
  214. self.didInitiallyRevealSearchBar = NO;
  215. }
  216. #pragma mark - Private
  217. - (void)setupToolbarItems {
  218. UIBarButtonItem *emptySpaceOrShare = UIBarButtonItem.flex_fixedSpace;
  219. if (self.showsShareToolbarItem) {
  220. emptySpaceOrShare = FLEXBarButtonItemSystem(Action, self, @selector(shareButtonPressed));
  221. }
  222. self.toolbarItems = @[
  223. UIBarButtonItem.flex_fixedSpace,
  224. UIBarButtonItem.flex_flexibleSpace,
  225. UIBarButtonItem.flex_fixedSpace,
  226. UIBarButtonItem.flex_flexibleSpace,
  227. UIBarButtonItem.flex_fixedSpace,
  228. UIBarButtonItem.flex_flexibleSpace,
  229. emptySpaceOrShare,
  230. UIBarButtonItem.flex_flexibleSpace,
  231. FLEXBarButtonItemSystem(Bookmarks, self, @selector(showBookmarks)),
  232. UIBarButtonItem.flex_flexibleSpace,
  233. FLEXBarButtonItemSystem(Organize, self, @selector(showTabSwitcher)),
  234. ];
  235. // Disable tabs entirely when not presented by FLEXExplorerViewController
  236. UIViewController *presenter = self.navigationController.presentingViewController;
  237. if (![presenter isKindOfClass:[FLEXExplorerViewController class]]) {
  238. self.toolbarItems.lastObject.enabled = NO;
  239. }
  240. }
  241. - (void)debounce:(void(^)(void))block {
  242. [self.debounceTimer invalidate];
  243. self.debounceTimer = [NSTimer
  244. scheduledTimerWithTimeInterval:self.searchBarDebounceInterval
  245. target:block
  246. selector:@selector(invoke)
  247. userInfo:nil
  248. repeats:NO
  249. ];
  250. }
  251. - (void)layoutTableHeaderIfNeeded {
  252. if (self.showsCarousel) {
  253. self.carousel.frame = FLEXRectSetHeight(
  254. self.carousel.frame, self.carousel.intrinsicContentSize.height
  255. );
  256. }
  257. self.tableView.tableHeaderView = self.tableView.tableHeaderView;
  258. [self.tableView layoutIfNeeded];
  259. }
  260. - (void)addCarousel:(FLEXScopeCarousel *)carousel {
  261. if (@available(iOS 11.0, *)) {
  262. self.tableView.tableHeaderView = carousel;
  263. } else {
  264. carousel.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
  265. CGRect frame = self.tableHeaderViewContainer.frame;
  266. CGRect subviewFrame = carousel.frame;
  267. subviewFrame.origin.y = 0;
  268. // Put the carousel below the search bar if it's already there
  269. if (self.showsSearchBar) {
  270. carousel.frame = subviewFrame = FLEXRectSetY(
  271. subviewFrame, self.searchController.searchBar.frame.size.height
  272. );
  273. frame.size.height += carousel.intrinsicContentSize.height;
  274. } else {
  275. frame.size.height = carousel.intrinsicContentSize.height;
  276. }
  277. self.tableHeaderViewContainer.frame = frame;
  278. [self.tableHeaderViewContainer addSubview:carousel];
  279. }
  280. [self layoutTableHeaderIfNeeded];
  281. }
  282. - (void)removeCarousel:(FLEXScopeCarousel *)carousel {
  283. [carousel removeFromSuperview];
  284. if (@available(iOS 11.0, *)) {
  285. self.tableView.tableHeaderView = nil;
  286. } else {
  287. if (self.showsSearchBar) {
  288. [self removeSearchController:self.searchController];
  289. [self addSearchController:self.searchController];
  290. } else {
  291. self.tableView.tableHeaderView = nil;
  292. _tableHeaderViewContainer = nil;
  293. }
  294. }
  295. }
  296. - (void)addSearchController:(UISearchController *)controller {
  297. if (@available(iOS 11.0, *)) {
  298. self.navigationItem.searchController = controller;
  299. } else {
  300. controller.searchBar.autoresizingMask |= UIViewAutoresizingFlexibleBottomMargin;
  301. [self.tableHeaderViewContainer addSubview:controller.searchBar];
  302. CGRect subviewFrame = controller.searchBar.frame;
  303. CGRect frame = self.tableHeaderViewContainer.frame;
  304. frame.size.width = MAX(frame.size.width, subviewFrame.size.width);
  305. frame.size.height = subviewFrame.size.height;
  306. // Move the carousel down if it's already there
  307. if (self.showsCarousel) {
  308. self.carousel.frame = FLEXRectSetY(
  309. self.carousel.frame, subviewFrame.size.height
  310. );
  311. frame.size.height += self.carousel.frame.size.height;
  312. }
  313. self.tableHeaderViewContainer.frame = frame;
  314. [self layoutTableHeaderIfNeeded];
  315. }
  316. }
  317. - (void)removeSearchController:(UISearchController *)controller {
  318. if (@available(iOS 11.0, *)) {
  319. self.navigationItem.searchController = nil;
  320. } else {
  321. [controller.searchBar removeFromSuperview];
  322. if (self.showsCarousel) {
  323. // self.carousel.frame = FLEXRectRemake(CGPointZero, self.carousel.frame.size);
  324. [self removeCarousel:self.carousel];
  325. [self addCarousel:self.carousel];
  326. } else {
  327. self.tableView.tableHeaderView = nil;
  328. _tableHeaderViewContainer = nil;
  329. }
  330. }
  331. }
  332. - (UIView *)tableHeaderViewContainer {
  333. if (!_tableHeaderViewContainer) {
  334. _tableHeaderViewContainer = [UIView new];
  335. self.tableView.tableHeaderView = self.tableHeaderViewContainer;
  336. }
  337. return _tableHeaderViewContainer;
  338. }
  339. - (void)showBookmarks {
  340. // TODO
  341. }
  342. - (void)showTabSwitcher {
  343. UINavigationController *nav = [[UINavigationController alloc]
  344. initWithRootViewController:[FLEXTabsViewController new]
  345. ];
  346. [self presentViewController:nav animated:YES completion:nil];
  347. }
  348. - (void)shareButtonPressed {
  349. }
  350. #pragma mark - Search Bar
  351. #pragma mark UISearchResultsUpdating
  352. - (void)updateSearchResultsForSearchController:(UISearchController *)searchController {
  353. [self.debounceTimer invalidate];
  354. NSString *text = searchController.searchBar.text;
  355. void (^updateSearchResults)() = ^{
  356. if (self.searchResultsUpdater) {
  357. [self.searchResultsUpdater updateSearchResults:text];
  358. } else {
  359. [self updateSearchResults:text];
  360. }
  361. };
  362. // Only debounce if we want to, and if we have a non-empty string
  363. // Empty string events are sent instantly
  364. if (text.length && self.searchBarDebounceInterval > kFLEXDebounceInstant) {
  365. [self debounce:updateSearchResults];
  366. } else {
  367. updateSearchResults();
  368. }
  369. }
  370. #pragma mark UISearchControllerDelegate
  371. - (void)willPresentSearchController:(UISearchController *)searchController {
  372. // Manually show cancel button for < iOS 13
  373. if (!@available(iOS 13, *) && self.automaticallyShowsSearchBarCancelButton) {
  374. [searchController.searchBar setShowsCancelButton:YES animated:YES];
  375. }
  376. }
  377. - (void)willDismissSearchController:(UISearchController *)searchController {
  378. // Manually hide cancel button for < iOS 13
  379. if (!@available(iOS 13, *) && self.automaticallyShowsSearchBarCancelButton) {
  380. [searchController.searchBar setShowsCancelButton:NO animated:YES];
  381. }
  382. }
  383. #pragma mark UISearchBarDelegate
  384. /// Not necessary in iOS 13; remove this when iOS 13 is the deployment target
  385. - (void)searchBar:(UISearchBar *)searchBar selectedScopeButtonIndexDidChange:(NSInteger)selectedScope {
  386. [self updateSearchResultsForSearchController:self.searchController];
  387. }
  388. #pragma mark Table view
  389. /// Not having a title in the first section looks weird with a rounded-corner table view style
  390. - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
  391. if (@available(iOS 13, *)) {
  392. if (self.style == UITableViewStyleInsetGrouped) {
  393. return @" ";
  394. }
  395. }
  396. return nil; // For plain/gropued style
  397. }
  398. @end