FLEXTableViewController.m 19 KB

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