FLEXTabsViewController.m 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. //
  2. // FLEXTabsViewController.m
  3. // FLEX
  4. //
  5. // Created by Tanner on 2/4/20.
  6. // Copyright © 2020 Flipboard. All rights reserved.
  7. //
  8. #import "FLEXTabsViewController.h"
  9. #import "FLEXNavigationController.h"
  10. #import "FLEXTabList.h"
  11. #import "FLEXBookmarkManager.h"
  12. #import "FLEXTableView.h"
  13. #import "FLEXUtility.h"
  14. #import "FLEXColor.h"
  15. #import "UIBarButtonItem+FLEX.h"
  16. #import "FLEXExplorerViewController.h"
  17. #import "FLEXGlobalsViewController.h"
  18. #import "FLEXBookmarksViewController.h"
  19. @interface FLEXTabsViewController ()
  20. @property (nonatomic, copy) NSArray<UINavigationController *> *openTabs;
  21. @property (nonatomic, copy) NSArray<UIImage *> *tabSnapshots;
  22. @property (nonatomic) NSInteger activeIndex;
  23. @property (nonatomic) BOOL presentNewActiveTabOnDismiss;
  24. @property (nonatomic, readonly) FLEXExplorerViewController *corePresenter;
  25. @end
  26. @implementation FLEXTabsViewController
  27. #pragma mark - Initialization
  28. - (id)init {
  29. return [self initWithStyle:UITableViewStylePlain];
  30. }
  31. - (void)viewDidLoad {
  32. [super viewDidLoad];
  33. self.title = @"Open Tabs";
  34. self.navigationController.hidesBarsOnSwipe = NO;
  35. self.tableView.allowsMultipleSelectionDuringEditing = YES;
  36. [self reloadData:NO];
  37. }
  38. - (void)viewWillAppear:(BOOL)animated {
  39. [super viewWillAppear:animated];
  40. [self setupDefaultBarItems];
  41. }
  42. - (void)viewDidAppear:(BOOL)animated {
  43. [super viewDidAppear:animated];
  44. // Instead of updating the active snapshot before we present,
  45. // we update it after we present to avoid pre-presenation latency
  46. dispatch_async(dispatch_get_main_queue(), ^{
  47. [FLEXTabList.sharedList updateSnapshotForActiveTab];
  48. [self reloadData:NO];
  49. [self.tableView reloadData];
  50. });
  51. }
  52. #pragma mark - Private
  53. /// @param trackActiveTabDelta whether to check if the active
  54. /// tab changed and needs to be presented upon "Done" dismissal.
  55. /// @return whether the active tab changed or not (if there are any tabs left)
  56. - (BOOL)reloadData:(BOOL)trackActiveTabDelta {
  57. BOOL activeTabDidChange = NO;
  58. FLEXTabList *list = FLEXTabList.sharedList;
  59. // Flag to enable check to determine whether
  60. if (trackActiveTabDelta) {
  61. NSInteger oldActiveIndex = self.activeIndex;
  62. if (oldActiveIndex != list.activeTabIndex && list.activeTabIndex != NSNotFound) {
  63. self.presentNewActiveTabOnDismiss = YES;
  64. activeTabDidChange = YES;
  65. } else if (self.presentNewActiveTabOnDismiss) {
  66. // If we had something to present before, now we don't
  67. // (i.e. activeTabIndex == NSNotFound)
  68. self.presentNewActiveTabOnDismiss = NO;
  69. }
  70. }
  71. // We assume the tabs aren't going to change out from under us, since
  72. // presenting any other tool via keyboard shortcuts should dismiss us first
  73. self.openTabs = list.openTabs;
  74. self.tabSnapshots = list.openTabSnapshots;
  75. self.activeIndex = list.activeTabIndex;
  76. return activeTabDidChange;
  77. }
  78. - (void)reloadActiveTabRowIfChanged:(BOOL)activeTabChanged {
  79. // Refresh the newly active tab row if needed
  80. if (activeTabChanged) {
  81. NSIndexPath *active = [NSIndexPath
  82. indexPathForRow:self.activeIndex inSection:0
  83. ];
  84. [self.tableView reloadRowsAtIndexPaths:@[active] withRowAnimation:UITableViewRowAnimationNone];
  85. }
  86. }
  87. - (void)setupDefaultBarItems {
  88. self.navigationItem.rightBarButtonItem = FLEXBarButtonItemSystem(Done, self, @selector(dismissAnimated));
  89. self.toolbarItems = @[
  90. UIBarButtonItem.flex_fixedSpace,
  91. UIBarButtonItem.flex_flexibleSpace,
  92. FLEXBarButtonItemSystem(Add, self, @selector(addTabButtonPressed:)),
  93. UIBarButtonItem.flex_flexibleSpace,
  94. FLEXBarButtonItemSystem(Edit, self, @selector(toggleEditing)),
  95. ];
  96. // Disable editing if no tabs available
  97. self.toolbarItems.lastObject.enabled = self.openTabs.count > 0;
  98. }
  99. - (void)setupEditingBarItems {
  100. self.navigationItem.rightBarButtonItem = nil;
  101. self.toolbarItems = @[
  102. [UIBarButtonItem itemWithTitle:@"Close All" target:self action:@selector(closeAllButtonPressed:)],
  103. UIBarButtonItem.flex_flexibleSpace,
  104. [UIBarButtonItem disabledSystemItem:UIBarButtonSystemItemAdd],
  105. UIBarButtonItem.flex_flexibleSpace,
  106. // We use a non-system done item because we change its title dynamically
  107. [UIBarButtonItem doneStyleitemWithTitle:@"Done" target:self action:@selector(toggleEditing)]
  108. ];
  109. self.toolbarItems.firstObject.tintColor = FLEXColor.destructiveColor;
  110. }
  111. - (FLEXExplorerViewController *)corePresenter {
  112. // We must be presented by a FLEXExplorerViewController, or presented
  113. // by another view controller that was presented by FLEXExplorerViewController
  114. FLEXExplorerViewController *presenter = (id)self.presentingViewController;
  115. presenter = (id)presenter.presentingViewController ?: presenter;
  116. NSAssert(
  117. [presenter isKindOfClass:[FLEXExplorerViewController class]],
  118. @"The tabs view controller expects to be presented by the explorer controller"
  119. );
  120. return presenter;
  121. }
  122. #pragma mark Button Actions
  123. - (void)dismissAnimated {
  124. if (self.presentNewActiveTabOnDismiss) {
  125. // The active tab was closed so we need to present the new one
  126. UIViewController *activeTab = FLEXTabList.sharedList.activeTab;
  127. FLEXExplorerViewController *presenter = self.corePresenter;
  128. [presenter dismissViewControllerAnimated:YES completion:^{
  129. [presenter presentViewController:activeTab animated:YES completion:nil];
  130. }];
  131. } else if (self.activeIndex == NSNotFound) {
  132. // The only tab was closed, so dismiss everything
  133. [self.corePresenter dismissViewControllerAnimated:YES completion:nil];
  134. } else {
  135. // Simple dismiss with the same active tab, only dismiss myself
  136. [self dismissViewControllerAnimated:YES completion:nil];
  137. }
  138. }
  139. - (void)toggleEditing {
  140. NSArray<NSIndexPath *> *selected = self.tableView.indexPathsForSelectedRows;
  141. self.editing = !self.editing;
  142. if (self.isEditing) {
  143. [self setupEditingBarItems];
  144. } else {
  145. [self setupDefaultBarItems];
  146. // Get index set of tabs to close
  147. NSMutableIndexSet *indexes = [NSMutableIndexSet new];
  148. for (NSIndexPath *ip in selected) {
  149. [indexes addIndex:ip.row];
  150. }
  151. if (selected.count) {
  152. // Close tabs and update data source
  153. [FLEXTabList.sharedList closeTabsAtIndexes:indexes];
  154. BOOL activeTabChanged = [self reloadData:YES];
  155. // Remove deleted rows
  156. [self.tableView deleteRowsAtIndexPaths:selected withRowAnimation:UITableViewRowAnimationAutomatic];
  157. // Refresh the newly active tab row if needed
  158. [self reloadActiveTabRowIfChanged:activeTabChanged];
  159. }
  160. }
  161. }
  162. - (void)addTabButtonPressed:(UIBarButtonItem *)sender {
  163. if (FLEXBookmarkManager.bookmarks.count) {
  164. [FLEXAlert makeSheet:^(FLEXAlert *make) {
  165. make.title(@"New Tab");
  166. make.button(@"Main Menu").handler(^(NSArray<NSString *> *strings) {
  167. [self addTabAndDismiss:[FLEXNavigationController
  168. withRootViewController:[FLEXGlobalsViewController new]
  169. ]];
  170. });
  171. make.button(@"Choose from Bookmarks").handler(^(NSArray<NSString *> *strings) {
  172. [self presentViewController:[FLEXNavigationController
  173. withRootViewController:[FLEXBookmarksViewController new]
  174. ] animated:YES completion:nil];
  175. });
  176. make.button(@"Cancel").cancelStyle();
  177. } showFrom:self source:sender];
  178. } else {
  179. // No bookmarks, just open the main menu
  180. [self addTabAndDismiss:[FLEXNavigationController
  181. withRootViewController:[FLEXGlobalsViewController new]
  182. ]];
  183. }
  184. }
  185. - (void)addTabAndDismiss:(UINavigationController *)newTab {
  186. FLEXExplorerViewController *presenter = self.corePresenter;
  187. [presenter dismissViewControllerAnimated:YES completion:^{
  188. [presenter presentViewController:newTab animated:YES completion:nil];
  189. }];
  190. }
  191. - (void)closeAllButtonPressed:(UIBarButtonItem *)sender {
  192. [FLEXAlert makeSheet:^(FLEXAlert *make) {
  193. NSInteger count = self.openTabs.count;
  194. NSString *title = FLEXPluralFormatString(count, @"Close %@ tabs", @"Close %@ tab");
  195. make.button(title).destructiveStyle().handler(^(NSArray<NSString *> *strings) {
  196. [self closeAll];
  197. [self toggleEditing];
  198. });
  199. make.button(@"Cancel").cancelStyle();
  200. } showFrom:self source:sender];
  201. }
  202. - (void)closeAll {
  203. NSInteger rowCount = self.openTabs.count;
  204. // Close tabs and update data source
  205. [FLEXTabList.sharedList closeAllTabs];
  206. [self reloadData:YES];
  207. // Delete rows from table view
  208. NSArray<NSIndexPath *> *allRows = [NSArray flex_forEachUpTo:rowCount map:^id(NSUInteger row) {
  209. return [NSIndexPath indexPathForRow:row inSection:0];
  210. }];
  211. [self.tableView deleteRowsAtIndexPaths:allRows withRowAnimation:UITableViewRowAnimationAutomatic];
  212. }
  213. #pragma mark - Table View Data Source
  214. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  215. return self.openTabs.count;
  216. }
  217. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  218. UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kFLEXDetailCell forIndexPath:indexPath];
  219. UINavigationController *tab = self.openTabs[indexPath.row];
  220. cell.imageView.image = self.tabSnapshots[indexPath.row];
  221. cell.textLabel.text = tab.topViewController.title;
  222. cell.detailTextLabel.text = FLEXPluralString(tab.viewControllers.count, @"pages", @"page");
  223. if (!cell.tag) {
  224. cell.textLabel.lineBreakMode = NSLineBreakByTruncatingTail;
  225. cell.textLabel.font = [UIFont preferredFontForTextStyle:UIFontTextStyleHeadline];
  226. cell.detailTextLabel.font = [UIFont preferredFontForTextStyle:UIFontTextStyleSubheadline];
  227. cell.tag = 1;
  228. }
  229. if (indexPath.row == self.activeIndex) {
  230. cell.backgroundColor = FLEXColor.secondaryBackgroundColor;
  231. } else {
  232. cell.backgroundColor = FLEXColor.primaryBackgroundColor;
  233. }
  234. return cell;
  235. }
  236. #pragma mark - Table View Delegate
  237. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
  238. if (self.editing) {
  239. // Case: editing with multi-select
  240. self.toolbarItems.lastObject.title = @"Close Selected";
  241. self.toolbarItems.lastObject.tintColor = FLEXColor.destructiveColor;
  242. } else {
  243. if (self.activeIndex == indexPath.row && self.corePresenter != self.presentingViewController) {
  244. // Case: selected the already active tab
  245. [self dismissAnimated];
  246. } else {
  247. // Case: selected a different tab,
  248. // or selected a tab when presented from the FLEX toolbar
  249. FLEXTabList.sharedList.activeTabIndex = indexPath.row;
  250. self.presentNewActiveTabOnDismiss = YES;
  251. [self dismissAnimated];
  252. }
  253. }
  254. }
  255. - (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
  256. NSParameterAssert(self.editing);
  257. if (tableView.indexPathsForSelectedRows.count == 0) {
  258. self.toolbarItems.lastObject.title = @"Done";
  259. self.toolbarItems.lastObject.tintColor = self.view.tintColor;
  260. }
  261. }
  262. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
  263. return YES;
  264. }
  265. - (void)tableView:(UITableView *)table
  266. commitEditingStyle:(UITableViewCellEditingStyle)edit
  267. forRowAtIndexPath:(NSIndexPath *)indexPath {
  268. NSParameterAssert(edit == UITableViewCellEditingStyleDelete);
  269. // Close tab and update data source
  270. [FLEXTabList.sharedList closeTab:self.openTabs[indexPath.row]];
  271. BOOL activeTabChanged = [self reloadData:YES];
  272. // Delete row from table view
  273. [table deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
  274. // Refresh the newly active tab row if needed
  275. [self reloadActiveTabRowIfChanged:activeTabChanged];
  276. }
  277. @end