FLEXTableViewController.m 16 KB

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