FLEXTableViewController.m 16 KB

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