FLEXTableViewController.m 16 KB

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