FLEXTableViewController.m 18 KB

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