FLEXTableViewController.m 19 KB

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