FLEXShortcutsSection.m 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. //
  2. // FLEXShortcutsSection.m
  3. // FLEX
  4. //
  5. // Created by Tanner Bennett on 8/29/19.
  6. // Copyright © 2019 Flipboard. All rights reserved.
  7. //
  8. #import "FLEXShortcutsSection.h"
  9. #import "FLEXTableView.h"
  10. #import "FLEXTableViewCell.h"
  11. #import "FLEXUtility.h"
  12. #import "FLEXShortcut.h"
  13. #import "FLEXProperty.h"
  14. #import "FLEXPropertyAttributes.h"
  15. #import "FLEXIvar.h"
  16. #import "FLEXMethod.h"
  17. #import "FLEXRuntime+UIKitHelpers.h"
  18. #pragma mark Private
  19. @interface FLEXShortcutsSection ()
  20. @property (nonatomic, copy) NSArray<NSString *> *titles;
  21. @property (nonatomic, copy) NSArray<NSString *> *subtitles;
  22. @property (nonatomic, copy) NSArray<NSString *> *allTitles;
  23. @property (nonatomic, copy) NSArray<NSString *> *allSubtitles;
  24. // Shortcuts are not used if initialized with static titles and subtitles
  25. @property (nonatomic, copy) NSArray<id<FLEXShortcut>> *shortcuts;
  26. @property (nonatomic, readonly) NSArray<id<FLEXShortcut>> *allShortcuts;
  27. @end
  28. @implementation FLEXShortcutsSection
  29. #pragma mark Initialization
  30. + (instancetype)forObject:(id)objectOrClass rowTitles:(NSArray<NSString *> *)titles {
  31. return [self forObject:objectOrClass rowTitles:titles rowSubtitles:nil];
  32. }
  33. + (instancetype)forObject:(id)objectOrClass
  34. rowTitles:(NSArray<NSString *> *)titles
  35. rowSubtitles:(NSArray<NSString *> *)subtitles {
  36. return [[self alloc] initWithObject:objectOrClass titles:titles subtitles:subtitles];
  37. }
  38. + (instancetype)forObject:(id)objectOrClass rows:(NSArray *)rows {
  39. return [[self alloc] initWithObject:objectOrClass rows:rows];
  40. }
  41. + (instancetype)forObject:(id)objectOrClass additionalRows:(NSArray *)toPrepend {
  42. NSArray *rows = [FLEXShortcutsFactory shortcutsForObjectOrClass:objectOrClass];
  43. NSArray *allRows = [toPrepend arrayByAddingObjectsFromArray:rows] ?: rows;
  44. return [self forObject:objectOrClass rows:allRows];
  45. }
  46. + (instancetype)forObject:(id)objectOrClass {
  47. return [self forObject:objectOrClass additionalRows:nil];
  48. }
  49. - (id)initWithObject:(id)object
  50. titles:(NSArray<NSString *> *)titles
  51. subtitles:(NSArray<NSString *> *)subtitles {
  52. NSParameterAssert(titles.count == subtitles.count || !subtitles);
  53. NSParameterAssert(titles.count);
  54. self = [super init];
  55. if (self) {
  56. _object = object;
  57. _allTitles = titles.copy;
  58. _allSubtitles = subtitles.copy;
  59. _numberOfLines = 1;
  60. }
  61. return self;
  62. }
  63. - (id)initWithObject:object rows:(NSArray *)rows {
  64. self = [super init];
  65. if (self) {
  66. _object = object;
  67. _allShortcuts = [rows flex_mapped:^id(id obj, NSUInteger idx) {
  68. return [FLEXShortcut shortcutFor:obj];
  69. }];
  70. _numberOfLines = 1;
  71. // Populate titles and subtitles
  72. [self reloadData];
  73. }
  74. return self;
  75. }
  76. #pragma mark - Public
  77. - (void)setCacheSubtitles:(BOOL)cacheSubtitles {
  78. if (_cacheSubtitles == cacheSubtitles) return;
  79. // cacheSubtitles only applies if we have shortcut objects
  80. if (self.allShortcuts) {
  81. _cacheSubtitles = cacheSubtitles;
  82. [self reloadData];
  83. } else {
  84. NSLog(@"Warning: setting 'cacheSubtitles' on a shortcut section with static subtitles");
  85. }
  86. }
  87. #pragma mark - Overrides
  88. - (UITableViewCellAccessoryType)accessoryTypeForRow:(NSInteger)row {
  89. if (_allShortcuts) {
  90. return [self.shortcuts[row] accessoryTypeWith:self.object];
  91. }
  92. return UITableViewCellAccessoryNone;
  93. }
  94. - (void)setFilterText:(NSString *)filterText {
  95. super.filterText = filterText;
  96. NSAssert(
  97. self.allTitles.count == self.allSubtitles.count,
  98. @"Each title needs a (possibly empty) subtitle"
  99. );
  100. if (filterText.length) {
  101. // Tally up indexes of titles and subtitles matching the filter
  102. NSMutableIndexSet *filterMatches = [NSMutableIndexSet new];
  103. id filterBlock = ^BOOL(NSString *obj, NSUInteger idx) {
  104. if ([obj localizedCaseInsensitiveContainsString:filterText]) {
  105. [filterMatches addIndex:idx];
  106. return YES;
  107. }
  108. return NO;
  109. };
  110. // Get all matching indexes, including subtitles
  111. [self.allTitles flex_forEach:filterBlock];
  112. [self.allSubtitles flex_forEach:filterBlock];
  113. // Filter to matching indexes only
  114. self.titles = [self.allTitles objectsAtIndexes:filterMatches];
  115. self.subtitles = [self.allSubtitles objectsAtIndexes:filterMatches];
  116. self.shortcuts = [self.allShortcuts objectsAtIndexes:filterMatches];
  117. } else {
  118. self.shortcuts = self.allShortcuts;
  119. self.titles = self.allTitles;
  120. self.subtitles = [self.allSubtitles flex_filtered:^BOOL(NSString *sub, NSUInteger idx) {
  121. return sub.length > 0;
  122. }];
  123. }
  124. }
  125. - (void)reloadData {
  126. // Generate all (sub)titles from shortcuts
  127. if (self.allShortcuts) {
  128. self.allTitles = [self.allShortcuts flex_mapped:^id(FLEXShortcut *s, NSUInteger idx) {
  129. return [s titleWith:self.object];
  130. }];
  131. self.allSubtitles = [self.allShortcuts flex_mapped:^id(FLEXShortcut *s, NSUInteger idx) {
  132. return [s subtitleWith:self.object] ?: @"";
  133. }];
  134. }
  135. // Re-generate filtered (sub)titles and shortcuts
  136. self.filterText = self.filterText;
  137. }
  138. - (NSString *)title {
  139. return @"Shortcuts";
  140. }
  141. - (NSInteger)numberOfRows {
  142. return self.titles.count;
  143. }
  144. - (BOOL)canSelectRow:(NSInteger)row {
  145. UITableViewCellAccessoryType type = [self.shortcuts[row] accessoryTypeWith:self.object];
  146. BOOL hasDisclosure = NO;
  147. hasDisclosure |= type == UITableViewCellAccessoryDisclosureIndicator;
  148. hasDisclosure |= type == UITableViewCellAccessoryDetailDisclosureButton;
  149. return hasDisclosure;
  150. }
  151. - (void (^)(__kindof UIViewController *))didSelectRowAction:(NSInteger)row {
  152. return [self.shortcuts[row] didSelectActionWith:self.object];
  153. }
  154. - (UIViewController *)viewControllerToPushForRow:(NSInteger)row {
  155. /// Nil if shortcuts is nil, i.e. if initialized with forObject:rowTitles:rowSubtitles:
  156. return [self.shortcuts[row] viewerWith:self.object];
  157. }
  158. - (void (^)(__kindof UIViewController *))didPressInfoButtonAction:(NSInteger)row {
  159. id<FLEXShortcut> shortcut = self.shortcuts[row];
  160. if ([shortcut respondsToSelector:@selector(editorWith:)]) {
  161. id object = self.object;
  162. return ^(UIViewController *host) {
  163. UIViewController *editor = [shortcut editorWith:object];
  164. [host.navigationController pushViewController:editor animated:YES];
  165. };
  166. }
  167. return nil;
  168. }
  169. - (NSString *)reuseIdentifierForRow:(NSInteger)row {
  170. FLEXTableViewCellReuseIdentifier defaultReuse = kFLEXDetailCell;
  171. if (@available(iOS 11, *)) {
  172. defaultReuse = kFLEXMultilineDetailCell;
  173. }
  174. return [self.shortcuts[row] customReuseIdentifierWith:self.object] ?: defaultReuse;
  175. }
  176. - (void)configureCell:(__kindof FLEXTableViewCell *)cell forRow:(NSInteger)row {
  177. cell.titleLabel.text = [self titleForRow:row];
  178. cell.titleLabel.numberOfLines = self.numberOfLines;
  179. cell.subtitleLabel.text = [self subtitleForRow:row];
  180. cell.subtitleLabel.numberOfLines = self.numberOfLines;
  181. cell.accessoryType = [self accessoryTypeForRow:row];
  182. }
  183. - (NSString *)titleForRow:(NSInteger)row {
  184. return self.titles[row];
  185. }
  186. - (NSString *)subtitleForRow:(NSInteger)row {
  187. // Case: dynamic, uncached subtitles
  188. if (!self.cacheSubtitles) {
  189. NSString *subtitle = [self.shortcuts[row] subtitleWith:self.object];
  190. return subtitle.length ? subtitle : nil;
  191. }
  192. // Case: static subtitles, or cached subtitles
  193. return self.subtitles[row];
  194. }
  195. @end
  196. #pragma mark - Global shortcut registration
  197. @interface FLEXShortcutsFactory () {
  198. BOOL _append, _prepend, _replace, _notInstance;
  199. NSArray<NSString *> *_properties, *_ivars, *_methods;
  200. }
  201. @end
  202. #define NewAndSet(ivar) ({ FLEXShortcutsFactory *r = [self new]; r->ivar = YES; r; })
  203. #define SetIvar(ivar) ({ self->ivar = YES; self; })
  204. #define SetParamBlock(ivar) ^(NSArray *p) { self->ivar = p; return self; }
  205. @implementation FLEXShortcutsFactory
  206. typedef NSMutableDictionary<Class, NSMutableArray<id<FLEXRuntimeMetadata>> *> RegistrationBuckets;
  207. // Class buckets
  208. static RegistrationBuckets *cProperties = nil;
  209. static RegistrationBuckets *cIvars = nil;
  210. static RegistrationBuckets *cMethods = nil;
  211. // Metaclass buckets
  212. static RegistrationBuckets *mProperties = nil;
  213. static RegistrationBuckets *mMethods = nil;
  214. + (void)load {
  215. cProperties = [NSMutableDictionary new];
  216. cIvars = [NSMutableDictionary new];
  217. cMethods = [NSMutableDictionary new];
  218. mProperties = [NSMutableDictionary new];
  219. mMethods = [NSMutableDictionary new];
  220. }
  221. + (NSArray<id<FLEXRuntimeMetadata>> *)shortcutsForObjectOrClass:(id)objectOrClass {
  222. NSMutableArray<id<FLEXRuntimeMetadata>> *shortcuts = [NSMutableArray new];
  223. BOOL isClass = object_isClass(objectOrClass);
  224. // The -class does not give you a metaclass, and we want a metaclass
  225. // if a class is passed in, or a class if an object is passed in
  226. Class classKey = object_getClass(objectOrClass);
  227. RegistrationBuckets *propertyBucket = isClass ? mProperties : cProperties;
  228. RegistrationBuckets *methodBucket = isClass ? mMethods : cMethods;
  229. RegistrationBuckets *ivarBucket = isClass ? nil : cIvars;
  230. BOOL stop = NO;
  231. while (!stop && classKey) {
  232. NSArray *properties = propertyBucket[classKey];
  233. NSArray *ivars = ivarBucket[classKey];
  234. NSArray *methods = methodBucket[classKey];
  235. // Stop if we found anything
  236. stop = properties || ivars || methods;
  237. if (stop) {
  238. // Add things we found to the list
  239. [shortcuts addObjectsFromArray:properties];
  240. [shortcuts addObjectsFromArray:ivars];
  241. [shortcuts addObjectsFromArray:methods];
  242. } else {
  243. classKey = class_getSuperclass(classKey);
  244. }
  245. }
  246. // .tag is used to cache whether the value of .isEditable;
  247. // This could change at runtime so it is important that
  248. // it is cached every time shortcuts are requeted and not
  249. // just once at as shortcuts are initially registered
  250. for (id<FLEXRuntimeMetadata> metadata in shortcuts) {
  251. metadata.tag = metadata.isEditable ? @YES : nil;
  252. }
  253. return shortcuts;
  254. }
  255. + (FLEXShortcutsFactory *)append {
  256. return NewAndSet(_append);
  257. }
  258. + (FLEXShortcutsFactory *)prepend {
  259. return NewAndSet(_prepend);
  260. }
  261. + (FLEXShortcutsFactory *)replace {
  262. return NewAndSet(_replace);
  263. }
  264. - (void)_register:(NSArray<id<FLEXRuntimeMetadata>> *)items to:(RegistrationBuckets *)global class:(Class)key {
  265. // Get (or initialize) the bucket for this class
  266. NSMutableArray *bucket = ({
  267. id bucket = global[key];
  268. if (!bucket) {
  269. bucket = [NSMutableArray new];
  270. global[(id)key] = bucket;
  271. }
  272. bucket;
  273. });
  274. if (self->_append) { [bucket addObjectsFromArray:items]; }
  275. if (self->_replace) { [bucket setArray:items]; }
  276. if (self->_prepend) {
  277. if (bucket.count) {
  278. // Set new items as array, add old items behind them
  279. id copy = bucket.copy;
  280. [bucket setArray:items];
  281. [bucket addObjectsFromArray:copy];
  282. } else {
  283. [bucket addObjectsFromArray:items];
  284. }
  285. }
  286. }
  287. - (FLEXShortcutsFactory *)class {
  288. return SetIvar(_notInstance);
  289. }
  290. - (FLEXShortcutsFactoryNames)properties {
  291. NSAssert(!_notInstance, @"Do not try to set properties+classProperties at the same time");
  292. return SetParamBlock(_properties);
  293. }
  294. - (FLEXShortcutsFactoryNames)classProperties {
  295. _notInstance = YES;
  296. return SetParamBlock(_properties);
  297. }
  298. - (FLEXShortcutsFactoryNames)ivars {
  299. return SetParamBlock(_ivars);
  300. }
  301. - (FLEXShortcutsFactoryNames)methods {
  302. NSAssert(!_notInstance, @"Do not try to set methods+classMethods at the same time");
  303. return SetParamBlock(_methods);
  304. }
  305. - (FLEXShortcutsFactoryNames)classMethods {
  306. _notInstance = YES;
  307. return SetParamBlock(_methods);
  308. }
  309. - (FLEXShortcutsFactoryTarget)forClass {
  310. return ^(Class cls) {
  311. NSAssert(
  312. ( self->_append && !self->_prepend && !self->_replace) ||
  313. (!self->_append && self->_prepend && !self->_replace) ||
  314. (!self->_append && !self->_prepend && self->_replace),
  315. @"You can only do one of [append, prepend, replace]"
  316. );
  317. /// Whether the metadata we're about to add is instance or
  318. /// class metadata, i.e. class properties vs instance properties
  319. BOOL instanceMetadata = !self->_notInstance;
  320. /// Whether the given class is a metaclass or not; we need to switch to
  321. /// the metaclass to add class metadata if we are given the normal class object
  322. BOOL isMeta = class_isMetaClass(cls);
  323. /// Whether the shortcuts we're about to add should appear for classes or instances
  324. BOOL instanceShortcut = !isMeta;
  325. if (instanceMetadata) {
  326. NSAssert(!isMeta,
  327. @"Instance metadata can only be added as an instance shortcut"
  328. );
  329. }
  330. Class metaclass = isMeta ? cls : object_getClass(cls);
  331. Class clsForMetadata = instanceMetadata ? cls : metaclass;
  332. RegistrationBuckets *propertyBucket = instanceShortcut ? cProperties : mProperties;
  333. RegistrationBuckets *methodBucket = instanceShortcut ? cMethods : mMethods;
  334. RegistrationBuckets *ivarBucket = instanceShortcut ? cIvars : nil;
  335. if (self->_properties) {
  336. NSArray *items = [self->_properties flex_mapped:^id(NSString *name, NSUInteger idx) {
  337. return [FLEXProperty named:name onClass:clsForMetadata];
  338. }];
  339. [self _register:items to:propertyBucket class:cls];
  340. }
  341. if (self->_methods) {
  342. NSArray *items = [self->_methods flex_mapped:^id(NSString *name, NSUInteger idx) {
  343. return [FLEXMethod selector:NSSelectorFromString(name) class:clsForMetadata];
  344. }];
  345. [self _register:items to:methodBucket class:cls];
  346. }
  347. if (self->_ivars) {
  348. NSAssert(instanceMetadata, @"Instance metadata can only be added as an instance shortcut (%@)", cls);
  349. NSArray *items = [self->_ivars flex_mapped:^id(NSString *name, NSUInteger idx) {
  350. return [FLEXIvar named:name onClass:clsForMetadata];
  351. }];
  352. [self _register:items to:ivarBucket class:cls];
  353. }
  354. };
  355. }
  356. @end