FLEXTableViewController.m 19 KB

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