text
stringlengths
9
39.2M
dir
stringlengths
26
295
lang
stringclasses
185 values
created_date
timestamp[us]
updated_date
timestamp[us]
repo_name
stringlengths
1
97
repo_full_name
stringlengths
7
106
star
int64
1k
183k
len_tokens
int64
1
13.8M
```objective-c #import "SPAutomatticTracker.h" #import "TracksService.h" @import AutomatticTracksModelObjC; static NSString *const TracksUserDefaultsAnonymousUserIDKey = @"TracksUserDefaultsAnonymousUserIDKey"; static NSString *const TracksUserDefaultsLoggedInUserIDKey = @"TracksUserDefaultsLoggedInUserIDKey"; static NSString *const TracksEventNamePrefix = @"spios"; static NSString *const TracksAuthenticatedUserTypeKey = @"simplenote:user_id"; @interface SPAutomatticTracker () @property (nonatomic, strong) TracksContextManager *contextManager; @property (nonatomic, strong) TracksService *tracksService; @property (nonatomic, strong) NSString *anonymousID; @property (nonatomic, strong) NSString *loggedInID; @end @implementation SPAutomatticTracker @synthesize loggedInID = _loggedInID; @synthesize anonymousID = _anonymousID; - (instancetype)init { self = [super init]; if (self) { TracksContextManager *contextManager = [TracksContextManager new]; NSParameterAssert(contextManager); TracksService *service = [[TracksService alloc] initWithContextManager:contextManager]; service.eventNamePrefix = TracksEventNamePrefix; service.authenticatedUserTypeKey = TracksAuthenticatedUserTypeKey; NSParameterAssert(service); _tracksService = service; _contextManager = contextManager; } return self; } + (instancetype)sharedInstance { static SPAutomatticTracker *_tracker = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _tracker = [self new]; }); return _tracker; } #pragma mark - Public Methods - (void)refreshMetadataWithEmail:(NSString *)email { NSParameterAssert(self.tracksService); NSMutableDictionary *userProperties = [NSMutableDictionary new]; userProperties[@"platform"] = @"iOS"; userProperties[@"accessibility_voice_over_enabled"] = @(UIAccessibilityIsVoiceOverRunning()); userProperties[@"is_rtl_language"] = @(UIApplication.sharedApplication.userInterfaceLayoutDirection == UIUserInterfaceLayoutDirectionRightToLeft); [self.tracksService.userProperties removeAllObjects]; [self.tracksService.userProperties addEntriesFromDictionary:userProperties]; if (self.loggedInID.length == 0) { // No previous username logged self.loggedInID = email; self.anonymousID = nil; [self.tracksService switchToAuthenticatedUserWithUsername:@"" userID:email skipAliasEventCreation:NO]; } else if ([self.loggedInID isEqualToString:email]){ // Username did not change from last call to this method just make sure Tracks client has it [self.tracksService switchToAuthenticatedUserWithUsername:@"" userID:email skipAliasEventCreation:YES]; } else { // Username changed for some reason switch back to anonymous first [self.tracksService switchToAnonymousUserWithAnonymousID:self.anonymousID]; [self.tracksService switchToAuthenticatedUserWithUsername:@"" userID:email skipAliasEventCreation:NO]; self.loggedInID = email; self.anonymousID = nil; } } - (void)refreshMetadataForAnonymousUser { NSParameterAssert(self.tracksService); [self.tracksService switchToAnonymousUserWithAnonymousID:self.anonymousID]; self.loggedInID = nil; } - (void)trackEventWithName:(NSString *)name properties:(NSDictionary *)properties { NSParameterAssert(name); NSParameterAssert(self.tracksService); [self.tracksService trackEventName:name withCustomProperties:properties]; if (properties == nil) { NSLog(@" Tracked: %@", name); } else { NSLog(@" Tracked: %@, properties: %@", name, properties); } } #pragma mark - Private property getter + setters - (NSString *)anonymousID { if (_anonymousID == nil || _anonymousID.length == 0) { NSString *anonymousID = [[NSUserDefaults standardUserDefaults] stringForKey:TracksUserDefaultsAnonymousUserIDKey]; if (anonymousID == nil) { anonymousID = [[NSUUID UUID] UUIDString]; [[NSUserDefaults standardUserDefaults] setObject:anonymousID forKey:TracksUserDefaultsAnonymousUserIDKey]; } _anonymousID = anonymousID; } return _anonymousID; } - (void)setAnonymousID:(NSString *)anonymousID { _anonymousID = anonymousID; if (anonymousID == nil) { [[NSUserDefaults standardUserDefaults] removeObjectForKey:TracksUserDefaultsAnonymousUserIDKey]; return; } [[NSUserDefaults standardUserDefaults] setObject:anonymousID forKey:TracksUserDefaultsAnonymousUserIDKey]; } - (NSString *)loggedInID { if (_loggedInID == nil || _loggedInID.length == 0) { NSString *loggedInID = [[NSUserDefaults standardUserDefaults] stringForKey:TracksUserDefaultsLoggedInUserIDKey]; if (loggedInID != nil) { _loggedInID = loggedInID; } } return _loggedInID; } - (void)setLoggedInID:(NSString *)loggedInID { _loggedInID = loggedInID; if (loggedInID == nil) { [[NSUserDefaults standardUserDefaults] removeObjectForKey:TracksUserDefaultsLoggedInUserIDKey]; return; } [[NSUserDefaults standardUserDefaults] setObject:loggedInID forKey:TracksUserDefaultsLoggedInUserIDKey]; } @end ```
/content/code_sandbox/Simplenote/Classes/SPAutomatticTracker.m
objective-c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
1,094
```swift import Foundation // MARK: - Editor Factory (!) // @objcMembers class EditorFactory: NSObject { /// Yet another Singleton /// static let shared = EditorFactory() /// Editor's Restoration Class /// var restorationClass: UIViewControllerRestoration.Type? /// Scroll position cache /// let scrollPositionCache: NoteScrollPositionCache = { let fileURL = FileManager.default.documentsURL.appendingPathComponent(Constants.filename) return NoteScrollPositionCache(storage: FileStorage(fileURL: fileURL)) }() /// You shall not pass! /// private override init() { super.init() } /// Returns a new Editor Instance /// func build(with note: Note?) -> SPNoteEditorViewController { assert(restorationClass != nil) let controller = SPNoteEditorViewController(note: note ?? newNote()) controller.restorationClass = restorationClass controller.restorationIdentifier = SPNoteEditorViewController.defaultRestorationIdentifier controller.scrollPositionCache = scrollPositionCache return controller } private func newNote() -> Note { let note = SPObjectManager.shared().newDefaultNote() if let tagName = SPAppDelegate.shared().filteredTagName { note.addTag(tagName) } return note } } // MARK: - Constants // private struct Constants { static let filename = ".scroll-cache" } ```
/content/code_sandbox/Simplenote/Classes/EditorFactory.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
291
```swift import UIKit // MARK: - UITextField // extension UITextField { /// Preprocess pasteboard content before pasting into tag text field /// @objc func pasteTag() { guard let selectedRange = selectedRange, let pasteboardText = UIPasteboard.general.string, !pasteboardText.isEmpty else { return } guard let tag = TagTextFieldInputValidator().preprocessForPasting(tag: pasteboardText), !tag.isEmpty else { return } guard delegate?.textField?(self, shouldChangeCharactersIn: selectedRange, replacementString: tag) == true else { return } insertText(tag) } } ```
/content/code_sandbox/Simplenote/Classes/UITextField+Tag.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
144
```swift import Foundation import UIKit // MARK: - SPTagHeaderView // @objc @objcMembers class SPTagHeaderView: UIView { /// Leading TitleLabel /// @IBOutlet private(set) var titleLabel: UILabel! /// Trailing ActionButton /// @IBOutlet private(set) var actionButton: UIButton! { didSet { actionButton.titleLabel?.adjustsFontForContentSizeCategory = true } } // MARK: - Overriden Methods override func awakeFromNib() { super.awakeFromNib() refreshStyle() } /// Updates the receiver's colors /// func refreshStyle() { titleLabel.textColor = .simplenoteTextColor actionButton.setTitleColor(.simplenoteInteractiveTextColor, for: .normal) } } ```
/content/code_sandbox/Simplenote/Classes/SPTagHeaderView.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
168
```swift import Foundation import UIKit // MARK: - Simplenote Named Images // @objc enum UIImageName: Int, CaseIterable { case add case allNotes case archive case arrowTopRight case checklist case checkmarkChecked case checkmarkUnchecked case chevronLeft case chevronRight case collaborate case copy case cross case crossOutlined case crossBig case crossBigOutlined case editor case ellipsis case ellipsisOutlined case hideKeyboard case history case info case link case mail case menu case newNote case note case pin case pinSmall case published case restore case search case settings case simplenoteLogo case share case shared case sortOrder case success case tag case tagViewDeletion case tags case tagsClosed case tagsOpen case taskChecked case taskUnchecked case trash case unpin case untagged case visibilityOn case visibilityOff case warning } // MARK: - Public Methods // extension UIImageName { /// Light Asset Filename /// var lightAssetFilename: String { switch self { case .add: return "icon_add" case .allNotes: return "icon_allnotes" case .archive: return "icon_archive" case .arrowTopRight: return "icon_arrow_top_right" case .checklist: return "icon_checklist" case .checkmarkChecked: return "icon_checkmark_checked" case .checkmarkUnchecked: return "icon_checkmark_unchecked" case .chevronLeft: return "icon_chevron_left" case .chevronRight: return "icon_chevron_right" case .collaborate: return "icon_collaborate" case .copy: return "icon_copy" case .cross: return "icon_cross" case .crossOutlined: return "icon_cross_outlined" case .crossBig: return "icon_cross_big" case .crossBigOutlined: return "icon_cross_big_outlined" case .editor: return "icon_editor" case .ellipsis: return "icon_ellipsis" case .ellipsisOutlined: return "icon_ellipsis_outline" case .hideKeyboard: return "icon_hide_keyboard" case .history: return "icon_history" case .info: return "icon_info" case .link: return "icon_link" case .mail: return "icon_mail" case .menu: return "icon_menu" case .newNote: return "icon_new_note" case .note: return "icon_note" case .pin: return "icon_pin" case .pinSmall: return "icon_pin_small" case .published: return "icon_published" case .restore: return "icon_restore" case .search: return "icon_search" case .settings: return "icon_settings" case .simplenoteLogo: return "simplenote-logo" case .share: return "icon_share" case .shared: return "icon_shared" case .sortOrder: return "icon_sort_order" case .success: return "icon_success" case .tag: return "icon_tag" case .tagViewDeletion: return "button_delete_small" case .tags: return "icon_tags" case .tagsClosed: return "icon_tags_close" case .tagsOpen: return "icon_tags_open" case .taskChecked: return "icon_task_checked" case .taskUnchecked: return "icon_task_unchecked" case .trash: return "icon_trash" case .unpin: return "icon_unpin" case .untagged: return "icon_untagged" case .visibilityOn: return "icon_visibility_on" case .visibilityOff: return "icon_visibility_off" case .warning: return "icon_warning" } } /// Dark Asset Filename /// var darkAssetFilename: String? { switch self { case .tagViewDeletion: return "button_delete_small_dark" default: return nil } } } ```
/content/code_sandbox/Simplenote/Classes/UIImageName.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
983
```objective-c // // Note.m // // Created by Michael Johnston on 01/07/08. // #import "Note.h" #import "NSString+Condensing.h" #import "NSString+Metadata.h" #import "JSONKit+Simplenote.h" #import "Simplenote-Swift.h" @interface Note (PrimitiveAccessors) - (NSString *)primitiveContent; - (void)setPrimitiveContent:(NSString *)newContent; @end @implementation Note @synthesize creationDatePreview; @synthesize modificationDatePreview; @synthesize titlePreview; @synthesize bodyPreview; @synthesize tagsArray; @dynamic content; @dynamic creationDate; @dynamic deleted; @dynamic lastPosition; @dynamic modificationDate; @dynamic publishURL; @dynamic shareURL; @dynamic systemTags; @dynamic tags; @dynamic pinned; @dynamic markdown; static NSDateFormatter *dateFormatterTime = nil; static NSDateFormatter *dateFormatterMonthDay = nil; static NSDateFormatter *dateFormatterMonthYear = nil; static NSDateFormatter *dateFormatterMonthDayYear = nil; static NSDateFormatter *dateFormatterMonthDayTime = nil; static NSDateFormatter *dateFormatterNumbers = nil; static NSCalendar *gregorian = nil; NSObject *notifyObject; SEL notifySelector; - (void) awakeFromFetch { [super awakeFromFetch]; [self createPreview]; [self updateTagsArray]; [self updateSystemTagsArray]; [self updateSystemTagFlags]; } - (void) awakeFromInsert { [super awakeFromInsert]; self.content = @""; self.publishURL = @""; self.shareURL = @""; self.creationDate = [NSDate date]; self.modificationDate = [NSDate date]; self.tags = @"[]"; self.systemTags = @"[]"; [self updateSystemTagsArray]; [self updateTagsArray]; } - (void)didTurnIntoFault { [super didTurnIntoFault]; } #pragma mark Properties // Accessors implemented below. All the "get" accessors simply return the value directly, with no additional // logic or steps for synchronization. The "set" accessors attempt to verify that the new value is definitely // different from the old value, to minimize the amount of work done. Any "set" which actually results in changing // data will mark the object as "dirty" - i.e., possessing data that has not been written to the database. // All the "set" accessors copy data, rather than retain it. This is common for value objects - strings, numbers, // dates, data buffers, etc. This ensures that subsequent changes to either the original or the copy don't violate // the encapsulation of the owning object. - (NSString *)localID { NSManagedObjectID *key = [self objectID]; if ([key isTemporaryID]) return nil; return [[key URIRepresentation] absoluteString]; } - (NSComparisonResult)compareModificationDate:(Note *)note { if (pinned && !note.pinned) return NSOrderedAscending; else if (!pinned && note.pinned) return NSOrderedDescending; //else if (pinned < note.pinned) return NSOrderedDescending; return [note.modificationDate compare:self.modificationDate]; } - (NSComparisonResult)compareModificationDateReverse:(Note *)note { if (pinned && !note.pinned) return NSOrderedAscending; else if (!pinned && note.pinned) return NSOrderedDescending; //else if (pinned < note.pinned) return NSOrderedDescending; return [self.modificationDate compare:note.modificationDate]; } - (NSComparisonResult)compareCreationDate:(Note *)note { if (pinned && !note.pinned) return NSOrderedAscending; else if (!pinned && note.pinned) return NSOrderedDescending; //else if (pinned < note.pinned) return NSOrderedDescending; return [note.creationDate compare:self.creationDate]; } - (NSComparisonResult)compareCreationDateReverse:(Note *)note { if (pinned && !note.pinned) return NSOrderedAscending; else if (!pinned && note.pinned) return NSOrderedDescending; //else if (pinned < note.pinned) return NSOrderedDescending; return [self.creationDate compare:note.creationDate]; } - (NSComparisonResult)compareAlpha:(Note *)note { if (pinned && !note.pinned) return NSOrderedAscending; else if (!pinned && note.pinned) return NSOrderedDescending; //else if (pinned < note.pinned) return NSOrderedDescending; return [self.content caseInsensitiveCompare:note.content]; } - (NSComparisonResult)compareAlphaReverse:(Note *)note { if (pinned && !note.pinned) return NSOrderedAscending; else if (!pinned && note.pinned) return NSOrderedDescending; //else if (pinned < note.pinned) return NSOrderedDescending; return [note.content caseInsensitiveCompare:self.content]; } - (BOOL)deleted { BOOL b; [self willAccessValueForKey:@"deleted"]; b = deleted; [self didAccessValueForKey:@"deleted"]; return b; } - (void)setDeleted:(BOOL) b { if (b == deleted) return; [self willChangeValueForKey:@"deleted"]; deleted = b; [self didChangeValueForKey:@"deleted"]; } - (BOOL)shared { return shared;//[self hasSystemTag:@"shared"]; } - (void)setShared:(BOOL) bShared { if (bShared) [self addSystemTag:@"shared"]; else [self stripSystemTag:@"shared"]; shared = bShared; } - (BOOL)published { return published;//[self hasSystemTag:@"published"]; } - (void)setPublished:(BOOL) bPublished { if (bPublished) [self addSystemTag:@"published"]; else [self stripSystemTag:@"published"]; published = bPublished; } - (BOOL)unread { return unread;// [self hasSystemTag:@"published"]; } - (void)setUnread:(BOOL) bUnread { if (bUnread) [self addSystemTag:@"unread"]; else [self stripSystemTag:@"unread"]; unread = bUnread; } - (void)setTags:(NSString *)newTags { if ((!tags && !newTags) || (tags && newTags && [tags isEqualToString:newTags])) return; [self willChangeValueForKey:@"tags"]; NSString *newString = [newTags copy]; [self setPrimitiveValue:newString forKey:@"tags"]; [self updateTagsArray]; [self didChangeValueForKey:@"tags"]; } // Maintain flags for performance purposes - (void)updateSystemTagFlags { pinned = [self hasSystemTag:@"pinned"]; shared = [self hasSystemTag:@"shared"]; published = [self hasSystemTag:@"published"]; unread = [self hasSystemTag:@"unread"]; markdown = [self hasSystemTag:@"markdown"]; } - (void)setSystemTags:(NSString *)newTags { if ((!systemTags && !newTags) || (systemTags && newTags && [systemTags isEqualToString:newTags])) return; [self willChangeValueForKey:@"systemTags"]; NSString *newString = [newTags copy]; [self setPrimitiveValue:newString forKey:@"systemTags"]; [self updateSystemTagsArray]; [self updateSystemTagFlags]; [self didChangeValueForKey:@"systemTags"]; } - (void)ensurePreviewStringsAreAvailable { if (self.titlePreview != nil) { return; } [self createPreview]; } - (BOOL)pinned { BOOL b; [self willAccessValueForKey:@"pinned"]; b = pinned; [self didAccessValueForKey:@"pinned"]; return b; } - (void)setPinned:(BOOL) bPinned { if (bPinned) [self addSystemTag:@"pinned"]; else [self stripSystemTag:@"pinned"]; [self willChangeValueForKey:@"pinned"]; pinned = bPinned; [self didChangeValueForKey:@"pinned"]; } - (BOOL)markdown { BOOL b; [self willAccessValueForKey:@"markdown"]; b = markdown; [self didAccessValueForKey:@"markdown"]; return b; } - (void)setMarkdown:(BOOL) bMarkdown { if (bMarkdown) [self addSystemTag:@"markdown"]; else [self stripSystemTag:@"markdown"]; [self willChangeValueForKey:@"markdown"]; markdown = bMarkdown; [self didChangeValueForKey:@"markdown"]; } - (int)lastPosition { int i; [self willAccessValueForKey:@"lastPosition"]; i = lastPosition; [self didAccessValueForKey:@"lastPosition"]; return i; } - (void)setLastPosition:(int) newLastPosition { if (lastPosition == newLastPosition) return; [self willChangeValueForKey:@"lastPosition"]; lastPosition = newLastPosition; [self didChangeValueForKey:@"lastPosition"]; } - (void)setShareURL:(NSString *)url { if ((!shareURL && !url) || (shareURL && url && [shareURL isEqualToString:url])) return; [self willChangeValueForKey:@"shareURL"]; NSString *newString = [url copy]; [self setPrimitiveValue:newString forKey:@"shareURL"]; [self didChangeValueForKey:@"shareURL"]; } - (void)setPublishURL:(NSString *)url { if ((!publishURL && !url) || (publishURL && url && [publishURL isEqualToString:url])) return; [self willChangeValueForKey:@"publishURL"]; NSString *newString = [url copy]; [self setPrimitiveValue:newString forKey:@"publishURL"]; [self didChangeValueForKey:@"publishURL"]; } - (NSString *)dateString:(NSDate *)date brief:(BOOL)brief { if (!gregorian) { gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian]; dateFormatterTime = [NSDateFormatter new]; [dateFormatterTime setTimeStyle: NSDateFormatterShortStyle]; //[dateFormatterTime setDateFormat:@"h:mm a"]; dateFormatterMonthDay = [NSDateFormatter new]; [dateFormatterMonthDay setDateFormat:NSLocalizedString(@"MMM d", @"Month and day date formatter")]; // [dateFormatterMonthDay setTimeStyle: kCFDateFormatterNoStyle]; // [dateFormatterMonthDay setDateStyle: kCFDateFormatterMediumStyle]; dateFormatterMonthYear = [NSDateFormatter new]; [dateFormatterMonthYear setDateFormat:NSLocalizedString(@"MMM yyyy", @"Month and year date formatter")]; //[dateFormatterMonthYear setDateStyle: kCFDateFormatterLongStyle]; //[dateFormatterMonthYear setTimeStyle: kCFDateFormatterShortStyle]; dateFormatterMonthDayYear = [NSDateFormatter new]; [dateFormatterMonthDayYear setDateFormat:NSLocalizedString(@"MMM d, yyyy", @"Month, day, and year date formatter")]; //[dateFormatterMonthDayYear setTimeStyle: kCFDateFormatterShortStyle]; dateFormatterMonthDayTime = [NSDateFormatter new]; [dateFormatterMonthDayTime setDateFormat:NSLocalizedString(@"MMM d, h:mm a", @"Month, day, and time date formatter")]; //[dateFormatterMonthDayTime setTimeStyle: kCFDateFormatterShortStyle]; dateFormatterNumbers = [NSDateFormatter new]; [dateFormatterNumbers setDateStyle: NSDateFormatterShortStyle]; //[dateFormatterMonthDayTime setTimeStyle: kCFDateFormatterShortStyle]; } //NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; NSDate *now = [NSDate date]; NSDateComponents *nowComponents = [gregorian components: NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMonth | NSCalendarUnitYear fromDate: now]; nowComponents.hour = 0; NSDate *nowMidnight = [gregorian dateFromComponents: nowComponents]; // Note: NSDateFormatter will convert the date to our local TZ. Issue #72 NSDate *then = date; NSDateComponents *deltaComponents = [gregorian components:NSCalendarUnitMinute | NSCalendarUnitYear fromDate: then toDate: nowMidnight options:NSCalendarWrapComponents]; nowComponents.day = 31; nowComponents.month = 12; NSDate *nowNewYear = [gregorian dateFromComponents: nowComponents]; NSDateComponents *deltaComponentsYear = [gregorian components: NSCalendarUnitDay | NSCalendarUnitYear fromDate: then toDate: nowNewYear options:0]; //NSLog(@"Comparing %@ to %@: %d", [then description], [nowMidnight description], deltaComponentsYear.year); NSString *dateString; if (deltaComponents.minute <= 0) { //[dateFormatter setDateFormat:@"h:mm a"]; NSString *todayStr = NSLocalizedString(@"Today", @"Displayed as a date in the case where a note was modified today, for example"); dateString = brief ? @"" : [todayStr stringByAppendingString:@", "]; dateString = [dateString stringByAppendingString: [dateFormatterTime stringFromDate:then]]; } else if (deltaComponents.minute < 60*24) { //[dateFormatter setDateFormat:@"h:mm a"]; NSString *yesterdayStr = NSLocalizedString(@"Yesterday", @"Displayed as a date in the case where a note was modified yesterday, for example"); if (brief) dateString = yesterdayStr; else { dateString = [yesterdayStr stringByAppendingString:@", "]; dateString = [dateString stringByAppendingString: [dateFormatterTime stringFromDate:then]]; } } else { if (deltaComponentsYear.year <= 0) { // This year if (!brief) { dateString = [dateFormatterMonthDay stringFromDate:then]; dateString = [dateString stringByAppendingFormat:@", %@", [dateFormatterTime stringFromDate:then]]; } else dateString = [dateFormatterMonthDay stringFromDate: then]; } else { // Previous years if (brief) dateString = [dateFormatterNumbers stringFromDate: then]; else dateString = [dateFormatterMonthDayYear stringFromDate: then]; } } return dateString; } - (NSString *)creationDateString:(BOOL)brief { return [self dateString:creationDate brief:brief]; } - (NSString *)modificationDateString:(BOOL)brief { return [self dateString:modificationDate brief:brief]; } - (void)setTagsFromList:(NSArray *)tagList { [self setTags: [tagList JSONString]]; } - (void)updateTagsArray { tagsArray = tags.length > 0 ? [[tags objectFromJSONString] mutableCopy] : [NSMutableArray arrayWithCapacity:2]; } - (BOOL)hasTags { if (tags == nil || tags.length == 0) return NO; return [tagsArray count] > 0; } - (BOOL)hasTag:(NSString *)tag { if (tags == nil || tags.length == 0) return NO; for (NSString *tagCheck in tagsArray) { if ([tagCheck compare:tag] == NSOrderedSame) return YES; } return NO; } - (void)addTag:(NSString *)tag { if (![self hasTag: tag]) { NSString *newTag = [tag copy]; [tagsArray addObject:newTag]; self.tags = [tagsArray JSONString]; } } - (void)updateSystemTagsArray { systemTagsArray = systemTags.length > 0 ? [[systemTags objectFromJSONString] mutableCopy] : [NSMutableArray arrayWithCapacity:2]; } - (void)addSystemTag:(NSString *)tag { if (![self hasSystemTag: tag]) { NSString *newTag = [tag copy]; [systemTagsArray addObject:newTag]; self.systemTags = [systemTagsArray JSONString]; } } - (BOOL)hasSystemTag:(NSString *)tag { if (systemTags == nil || systemTags.length == 0) return NO; for (NSString *tagCheck in systemTagsArray) { if ([tagCheck compare:tag] == NSOrderedSame) return YES; } return NO; } - (void)stripTag:(NSString *)tag { if (tags.length == 0) return; NSMutableArray *tagsArrayCopy = [tagsArray copy]; for (NSString *tagCheck in tagsArrayCopy) { if ([tagCheck compare:tag] == NSOrderedSame) { [tagsArray removeObject:tagCheck]; continue; } } self.tags = [tagsArray JSONString]; } - (void)setSystemTagsFromList:(NSArray *)tagList { [self setSystemTags: [tagList JSONString]]; } - (void)stripSystemTag:(NSString *)tag { if (systemTags.length == 0) return; NSMutableArray *systemTagsArrayCopy = [systemTagsArray copy]; for (NSString *tagCheck in systemTagsArrayCopy) { if ([tagCheck compare:tag] == NSOrderedSame) { [systemTagsArray removeObject:tagCheck]; continue; } } self.systemTags = [systemTagsArray JSONString]; } - (NSDictionary *)noteDictionaryWithContent:(BOOL)include { NSMutableDictionary *note = [[NSMutableDictionary alloc] init]; if (remoteId != nil && [remoteId length] > 1) [note setObject:remoteId forKey:@"key"]; [note setObject:deleted ? @"1" : @"0" forKey:@"deleted"]; [note setObject:[tags stringArray] forKey:@"tags"]; [note setObject:[systemTags stringArray] forKey:@"systemtags"]; [note setObject:[NSNumber numberWithDouble:[modificationDate timeIntervalSince1970]] forKey:@"modifydate"]; [note setObject:[NSNumber numberWithDouble:[creationDate timeIntervalSince1970]] forKey:@"createdate"]; if (include) { [note setObject:content forKey:@"content"]; } return note; } - (BOOL)isList { // Quick and dirty for now to avoid having to upgrade the database again with another flag NSRange newlineRange = [content rangeOfString:@"\n"]; if (newlineRange.location == NSNotFound || newlineRange.location+newlineRange.length+2 > content.length) return NO; return [content compare:@"- " options:0 range:NSMakeRange(newlineRange.location+newlineRange.length, 2)] == NSOrderedSame; } @end ```
/content/code_sandbox/Simplenote/Classes/Note.m
objective-c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
3,931
```swift import Foundation import UIKit // MARK: - SPLabel: Standard UIKit Label with extra properties. And batteries! // @IBDesignable class SPLabel: UILabel { /// # Insets to be applied over the actual text /// @IBInspectable var textInsets = UIEdgeInsets.zero // MARK: - Overrides override func drawText(in rect: CGRect) { super.drawText(in: rect.inset(by: textInsets)) } override var intrinsicContentSize: CGSize { let size = super.intrinsicContentSize return CGSize(width: size.width + textInsets.left + textInsets.right, height: size.height + textInsets.top + textInsets.bottom) } } ```
/content/code_sandbox/Simplenote/Classes/SPLabel.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
144
```swift import Foundation // MARK: - Color Studio Constants // Ref. path_to_url // enum ColorStudio: String { case black = "000000" case blue0 = "e9eff5" case blue5 = "c5d9ed" case blue10 = "9ec2e6" case blue20 = "72aee6" case blue30 = "5198d9" case blue40 = "3582c4" case blue50 = "2271b1" case blue60 = "135e96" case blue70 = "0a4b78" case blue80 = "043959" case blue90 = "01263a" case blue100 = "00131c" case celadon0 = "e4f2ed" case celadon5 = "a7e8d4" case celadon10 = "63d6b6" case celadon20 = "2ebd99" case celadon30 = "09a884" case celadon40 = "009172" case celadon50 = "007e65" case celadon60 = "006753" case celadon70 = "005042" case celadon80 = "003b30" case celadon90 = "002721" case celadon100 = "001c17" case darkGray1 = "1C1C1E" case darkGray2 = "2C2C2E" case darkGray3 = "3A3A3C" case darkGray4 = "545458" case gray0 = "f6f7f7" case gray5 = "dcdcde" case gray10 = "c3c4c7" case gray20 = "a7aaad" case gray30 = "8c8f94" case gray40 = "787c82" case gray50 = "646970" case gray60 = "50575e" case gray70 = "3c434a" case gray80 = "2c3338" case gray90 = "1d2327" case gray100 = "101517" case green0 = "e6f2e8" case green5 = "b8e6bf" case green10 = "68de86" case green20 = "1ed15a" case green30 = "00ba37" case green40 = "00a32a" case green50 = "008a20" case green60 = "007017" case green70 = "005c12" case green80 = "00450c" case green90 = "003008" case green100 = "001c05" case orange0 = "f5ece6" case orange5 = "f7dcc6" case orange10 = "ffbf86" case orange20 = "faa754" case orange30 = "e68b28" case orange40 = "d67709" case orange50 = "b26200" case orange60 = "8a4d00" case orange70 = "704000" case orange80 = "543100" case orange90 = "361f00" case orange100 = "1f1200" case pink0 = "f5e9ed" case pink5 = "f2ceda" case pink10 = "f7a8c3" case pink20 = "f283aa" case pink30 = "eb6594" case pink40 = "e34c84" case pink50 = "c9356e" case pink60 = "ab235a" case pink70 = "8c1749" case pink80 = "700f3b" case pink90 = "4f092a" case pink100 = "260415" case purple0 = "f2e9ed" case purple5 = "ebcee0" case purple10 = "e3afd5" case purple20 = "d48fc8" case purple30 = "c475bd" case purple40 = "b35eb1" case purple50 = "984a9c" case purple60 = "7c3982" case purple70 = "662c6e" case purple80 = "4d2054" case purple90 = "35163b" case purple100 = "1e0c21" case red0 = "f7ebec" case red5 = "facfd2" case red10 = "ffabaf" case red20 = "ff8085" case red30 = "f86368" case red40 = "e65054" case red50 = "d63638" case red60 = "b32d2e" case red70 = "8a2424" case red80 = "691c1c" case red90 = "451313" case red100 = "240a0a" case spBlue0 = "e9ecf5" case spBlue5 = "ced9f2" case spBlue10 = "abc1f5" case spBlue20 = "84a4f0" case spBlue30 = "618df2" case spBlue40 = "4678eb" case spBlue50 = "3361cc" case spBlue60 = "1d4fc4" case spBlue70 = "113ead" case spBlue80 = "0d2f85" case spBlue90 = "09205c" case spBlue100 = "05102e" case spGray1 = "f9f9f9" case spGray2 = "efeff0" case spGray3 = "ededed" case spYellow0 = "FE9500" case spYellow10 = "FE9F0A" case white = "FFFFFF" case wpBlue0 = "e6f1f5" case wpBlue5 = "bedae6" case wpBlue10 = "98c6d9" case wpBlue20 = "6ab3d0" case wpBlue30 = "3895ba" case wpBlue40 = "187aa2" case wpBlue50 = "006088" case wpBlue60 = "004e6e" case wpBlue70 = "003c56" case wpBlue80 = "002c40" case wpBlue90 = "001d2d" case wpBlue100 = "00101c" case yellow0 = "f5f1e1" case yellow5 = "f5e6b3" case yellow10 = "f2d76b" case yellow20 = "f0c930" case yellow30 = "deb100" case yellow40 = "c08c00" case yellow50 = "9d6e00" case yellow60 = "7d5600" case yellow70 = "674600" case yellow80 = "4f3500" case yellow90 = "302000" case yellow100 = "1c1300" } ```
/content/code_sandbox/Simplenote/Classes/ColorStudio.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
1,753
```swift import Foundation // MARK: - Represents all of the available Themes // @objc enum Theme: Int, CaseIterable { /// Darkness! /// case dark /// Old School Light /// case light /// Matches the System Settings /// case system /// Returns a localized Description, matching the current rawValue /// var description: String { switch self { case .dark: return NSLocalizedString("Dark", comment: "Theme: Dark") case .light: return NSLocalizedString("Light", comment: "Theme: Light") case .system: return NSLocalizedString("System Default", comment: "Theme: Matches iOS Settings") } } } extension Theme { static var allThemes: [Theme] { return [.dark, .light, .system] } static var legacyThemes: [Theme] { return [.dark, .light] } static var defaultThemeForCurrentOS: Theme { return .system } } ```
/content/code_sandbox/Simplenote/Classes/Theme.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
214
```swift import UIKit class SPAboutViewController: UIViewController { private let tableView = HuggableTableView(frame: .zero, style: .grouped) private let containerView = UIStackView() private let doneButton = RoundedCrossButton() private var viewSpinner: ViewSpinner? override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .simplenoteBlue50Color setupContainerView() setupDoneButton() setupHeaderView() setupTableView() setupFooterView() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) viewSpinner?.stop() } } // MARK: - Configuration // private extension SPAboutViewController { func setupDoneButton() { doneButton.translatesAutoresizingMaskIntoConstraints = false doneButton.addTarget(self, action: #selector(onDoneTap(_:)), for: .touchUpInside) doneButton.style = .blue view.addSubview(doneButton) NSLayoutConstraint.activate([ doneButton.topAnchor.constraint(equalTo: view.layoutMarginsGuide.topAnchor, constant: Constants.doneButtonTopMargin), doneButton.trailingAnchor.constraint(equalTo: view.layoutMarginsGuide.trailingAnchor), doneButton.widthAnchor.constraint(equalToConstant: Constants.doneButtonSideSize), doneButton.heightAnchor.constraint(equalToConstant: Constants.doneButtonSideSize), ]) } func setupContainerView() { let scrollView = UIScrollView() containerView.translatesAutoresizingMaskIntoConstraints = false containerView.axis = .vertical containerView.alignment = .fill containerView.spacing = Constants.containerSpacing scrollView.addFillingSubview(containerView, edgeInsets: Constants.containerEdgeInsets) view.addFillingSubview(scrollView) containerView.widthAnchor.constraint(equalTo: view.widthAnchor, constant: -(Constants.containerEdgeInsets.left + Constants.containerEdgeInsets.right)).isActive = true } func setupTableView() { tableView.delegate = self tableView.dataSource = self tableView.separatorColor = .simplenoteBlue30Color tableView.backgroundColor = UIColor.clear // Removing unneeded paddings tableView.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: CGFloat.leastNormalMagnitude)) tableView.tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: CGFloat.leastNormalMagnitude)) tableView.indicatorStyle = .white containerView.addArrangedSubview(tableView) } } // MARK: - Header Configuration // private extension SPAboutViewController { func setupHeaderView() { let stackView = UIStackView() stackView.alignment = .center stackView.axis = .vertical stackView.spacing = Constants.headerViewSpacing let logoView = self.logoView() setupSpinner(with: logoView) stackView.addArrangedSubview(logoView) stackView.addArrangedSubview(appNameLabel()) stackView.addArrangedSubview(versionLabel()) containerView.addArrangedSubview(stackView) } func logoView() -> UIView { let imageView = UIImageView(image: .image(name: .simplenoteLogo)) imageView.translatesAutoresizingMaskIntoConstraints = false imageView.tintColor = .white NSLayoutConstraint.activate([ imageView.widthAnchor.constraint(equalToConstant: Constants.logoWidth), imageView.heightAnchor.constraint(equalToConstant: Constants.logoWidth) ]) return imageView } func appNameLabel() -> UIView { let label = UILabel() label.text = Bundle.main.infoDictionary!["CFBundleName"] as? String label.textColor = UIColor.white label.font = UIFont.preferredFont(for: .largeTitle, weight: .bold) label.textAlignment = .center return label } func versionLabel() -> UIView { let label = UILabel() let versionNumber = Bundle.main.shortVersionString label.text = String(format: NSLocalizedString("Version %@", comment: "App version number"), versionNumber) label.textColor = UIColor.white label.font = UIFont.preferredFont(forTextStyle: .body) label.textAlignment = .center return label } } // MARK: - Footer Configuration // private extension SPAboutViewController { func setupFooterView() { let stackView = UIStackView() stackView.axis = .vertical stackView.alignment = .fill stackView.spacing = Constants.footerViewSpacing stackView.addArrangedSubview(footerServiceTextView()) containerView.addArrangedSubview(stackView) } func footerServiceTextView() -> UITextView { let textView = UITextView() textView.translatesAutoresizingMaskIntoConstraints = false textView.backgroundColor = UIColor.clear textView.isEditable = false textView.isScrollEnabled = false textView.textContainerInset = .zero textView.linkTextAttributes = [.foregroundColor: UIColor.simplenoteBlue10Color] textView.attributedText = footerAttributedText() return textView } func footerAttributedText() -> NSMutableAttributedString { let privacyText = footerAttributedText(Constants.privacyString, withLink: Constants.privacyURLString) let termsOfServiceText = footerAttributedText(Constants.termsString, withLink: Constants.termsURLString) let californiaStringText = footerAttributedText(Constants.californiaString, withLink: Constants.californiaURLString) let text = NSMutableAttributedString() text.append(privacyText) text.append(footerAttributedText(", ")) text.append(termsOfServiceText) text.append(footerAttributedText(",")) text.append(footerAttributedText("\n")) text.append(californiaStringText) let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.alignment = .center paragraphStyle.lineSpacing = Constants.footerLineSpacing text.addAttribute(.paragraphStyle, value: paragraphStyle, range: text.fullRange) return text } func footerAttributedText(_ text: String, withLink link: String) -> NSAttributedString { return NSAttributedString(string: text, attributes: [ .font: UIFont.preferredFont(forTextStyle: .footnote), .underlineStyle: NSUnderlineStyle.single.rawValue, .link: link ]) } func footerAttributedText(_ text: String) -> NSAttributedString { return NSAttributedString(string: text, attributes: [ .foregroundColor: UIColor.simplenoteBlue10Color, .font: UIFont.preferredFont(forTextStyle: .footnote) ]) } let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.font = UIFont.preferredFont(forTextStyle: .subheadline) label.textAlignment = .center label.textColor = .white return label } let formatter = DateFormatter() formatter.dateFormat = "yyyy" return String(format: "\u{00A9} Automattic %@", formatter.string(from: Date())) } } // MARK: - UITableViewDataSource Conformance // extension SPAboutViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return Constants.titles.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell(style: UITableViewCell.CellStyle.subtitle, reuseIdentifier: nil) cell.textLabel?.text = Constants.titles[indexPath.row] cell.detailTextLabel?.text = Constants.descriptions[indexPath.row] cell.textLabel?.textColor = .white cell.detailTextLabel?.textColor = .simplenoteBlue10Color cell.detailTextLabel?.font = .preferredFont(forTextStyle: .subheadline) cell.backgroundColor = .clear let bgColorView = UIView() bgColorView.backgroundColor = .simplenoteBlue30Color cell.selectedBackgroundView = bgColorView let arrowAccessoryView = UIImageView(image: .image(name: .arrowTopRight)) arrowAccessoryView.tintColor = .simplenoteBlue10Color arrowAccessoryView.frame = CGRect(x: 0, y: 0, width: Constants.cellAccessorySideSize, height: Constants.cellAccessorySideSize) cell.accessoryView = arrowAccessoryView return cell } } // MARK: - UITableViewDelegate Conformance // extension SPAboutViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { UIApplication.shared.open(Constants.urls[indexPath.row]) tableView.deselectRow(at: indexPath, animated: false) } @objc func onDoneTap(_ sender: UIButton) { dismiss(animated: true) } } // MARK: - Header Spinner // private extension SPAboutViewController { func setupSpinner(with view: UIView) { let gestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(handleSpinnerGestureRecognizer(_:))) gestureRecognizer.minimumPressDuration = Constants.logoMinPressDuration view.addGestureRecognizer(gestureRecognizer) view.isUserInteractionEnabled = true viewSpinner = ViewSpinner(view: view) viewSpinner?.onMaxVelocity = { [weak self] in self?.viewSpinner?.stop() self?.showSpinnerMessage() } } @objc func handleSpinnerGestureRecognizer(_ gestureRecognizer: UIGestureRecognizer) { switch gestureRecognizer.state { case .began: viewSpinner?.start() case .ended, .cancelled, .failed: viewSpinner?.stop() case .possible, .changed: break @unknown default: break } } func showSpinnerMessage() { guard let message = randomSpinnerMessage else { return } let alertController = UIAlertController(title: nil, message: message, preferredStyle: .alert) alertController.addCancelActionWithTitle(NSLocalizedString("OK", comment: "Closes alert controller for spinner on About view")) present(alertController, animated: true, completion: nil) } var randomSpinnerMessage: String? { Constants.spinnerMessages.randomElement().map { let preparedString = $0.replacingOccurrences(of: "&#x(..);", with: #"\\u00$1"#, options: .regularExpression, range: $0.fullRange) let resultString = NSMutableString(string: preparedString) CFStringTransform(resultString, nil, "Any-Hex/Java" as CFString, true) return resultString as String } } } // MARK: - Constants // private enum Constants { static let doneButtonSideSize: CGFloat = 30 static let doneButtonTopMargin: CGFloat = 13 static let logoWidth: CGFloat = 60 static let cellAccessorySideSize: CGFloat = 24 static let containerEdgeInsets = UIEdgeInsets(top: 72, left: 0, bottom: 14, right: 0) static let containerSpacing: CGFloat = 36 static let headerViewSpacing: CGFloat = 6 static let footerViewSpacing: CGFloat = 20 static let footerLineSpacing: CGFloat = 15 static let logoMinPressDuration: TimeInterval = 0.5 static let privacyString = NSLocalizedString("Privacy Policy", comment: "Simplenote privacy policy") static let privacyURLString = "path_to_url" static let termsString = NSLocalizedString("Terms of Service", comment: "Simplenote terms of service") static let termsURLString = "path_to_url" static let californiaString = NSLocalizedString("Privacy Notice for California Users", comment: "Simplenote terms of service") static let californiaURLString = "path_to_url#california-consumer-privacy-act-ccpa" static let titles: [String] = [ NSLocalizedString("Blog", comment: "The Simplenote blog"), "Twitter", NSLocalizedString("Get Help", comment: "FAQ or contact us"), NSLocalizedString("Rate Us", comment: "Rate on the App Store"), NSLocalizedString("Contribute", comment: "Contribute to the Simplenote apps on github"), NSLocalizedString("Careers", comment: "Work at Automattic") ] static let descriptions: [String] = [ "simplenote.com/blog", "@simplenoteapp", NSLocalizedString("FAQ or contact us", comment: "Get Help Description Label"), "App Store", "github.com", NSLocalizedString("Are you a developer? Were hiring.", comment: "Automattic hiring description") ] static let urls: [URL] = [ URL(string: "path_to_url")!, URL(string: "path_to_url")!, URL(string: "path_to_url")!, URL(string: "path_to_url")!, URL(string: "path_to_url")!, URL(string: "path_to_url")! ] static let spinnerMessages: [String] = [ "&#x49;&#x74;\\u0020&#x66;\\u0065\\u0065&#x6c;\\u0073&#x20;&#x6c;\\u0069&#x6b;\\u0065\\u0020&#x49;\\u0020\\u006f&#x6e;\\u006c&#x79;\\u0020&#x67;\\u006f&#x20;\\u0062\\u0061\\u0063&#x6b;\\u0077\\u0061&#x72;\\u0064&#x73;\\u002c\\u0020\\u0062&#x61;\\u0062\\u0079", "&#x54;\\u0075&#x72;&#x6e;\\u0020&#x61;&#x72;\\u006f&#x75;\\u006e&#x64;\\u002c\\u0020\\u0062\\u0072&#x69;\\u0067\\u0068\\u0074\\u0020&#x65;&#x79;&#x65;\\u0073\n&#x45;\\u0076\\u0065&#x72;\\u0079&#x20;&#x6e;&#x6f;\\u0077&#x20;\\u0061&#x6e;&#x64;&#x20;\\u0074&#x68;\\u0065\\u006e\\u0020&#x49;\\u0020&#x66;&#x61;\\u006c&#x6c;\\u0020\\u0061&#x70;&#x61;\\u0072&#x74;", "\\u0054&#x6f;\\u0020&#x65;&#x76;\\u0065&#x72;&#x79;&#x74;&#x68;\\u0069&#x6e;\\u0067&#x20;&#x28;&#x74;&#x75;\\u0072\\u006e&#x2c;\\u0020&#x74;&#x75;&#x72;\\u006e&#x2c;\\u0020&#x74;\\u0075&#x72;\\u006e\\u0029\n\\u0054\\u0068&#x65;\\u0072\\u0065&#x20;\\u0069\\u0073\\u0020\\u0061&#x20;\\u0073&#x65;\\u0061\\u0073&#x6f;\\u006e&#x20;\\u0028&#x74;\\u0075\\u0072&#x6e;\\u002c\\u0020\\u0074&#x75;\\u0072\\u006e\\u002c\\u0020&#x74;\\u0075\\u0072&#x6e;\\u0029", "&#x59;\\u006f\\u0075&#x20;\\u0073\\u0070\\u0069&#x6e;\\u0020&#x6d;\\u0065&#x20;\\u0072\\u0069\\u0067&#x68;\\u0074\\u0020\\u0072&#x6f;&#x75;\\u006e\\u0064&#x2c;\\u0020\\u0062&#x61;&#x62;&#x79;\n&#x52;&#x69;&#x67;&#x68;&#x74;&#x20;&#x72;\\u006f\\u0075\\u006e&#x64;\\u0020\\u006c&#x69;\\u006b\\u0065\\u0020&#x61;&#x20;\\u0072\\u0065&#x63;\\u006f&#x72;\\u0064&#x2c;\\u0020\\u0062&#x61;\\u0062\\u0079\n\\u0052\\u0069&#x67;\\u0068\\u0074&#x20;\\u0072&#x6f;\\u0075\\u006e&#x64;\\u002c\\u0020&#x72;\\u006f&#x75;\\u006e\\u0064\\u002c\\u0020&#x72;\\u006f\\u0075&#x6e;\\u0064", "\\u0041&#x6c;\\u006c\\u0020&#x74;&#x68;\\u0065&#x20;\\u0067\\u0072&#x65;&#x61;&#x74;&#x20;&#x74;\\u0068&#x69;&#x6e;\\u0067\\u0073\\u0020&#x61;\\u0072&#x65;\\u0020&#x73;&#x69;\\u006d&#x70;\\u006c&#x65;\\u002e\n\\u002d&#x20;\\u0057\\u0069\\u006e&#x73;\\u0074&#x6f;&#x6e;\\u0020&#x43;\\u0068&#x75;\\u0072\\u0063&#x68;\\u0069\\u006c&#x6c;", "\\u0053\\u0069&#x6d;\\u0070\\u006c\\u0069&#x63;\\u0069\\u0074&#x79;\\u0020\\u0069&#x73;\\u0020\\u0074\\u0068\\u0065\\u0020&#x67;&#x6c;&#x6f;\\u0072\\u0079\\u0020&#x6f;&#x66;&#x20;&#x65;\\u0078&#x70;&#x72;&#x65;&#x73;\\u0073\\u0069&#x6f;\\u006e\\u002e\n\\u002d\\u0020&#x57;&#x61;\\u006c&#x74;\\u0020\\u0057&#x68;\\u0069\\u0074\\u006d&#x61;\\u006e", "&#x4d;\\u0061\\u006b&#x65;&#x20;&#x65;\\u0076&#x65;\\u0072&#x79;\\u0074\\u0068\\u0069\\u006e\\u0067&#x20;\\u0061&#x73;\\u0020\\u0073&#x69;\\u006d\\u0070\\u006c\\u0065&#x20;\\u0061&#x73;\\u0020&#x70;\\u006f&#x73;\\u0073\\u0069\\u0062&#x6c;\\u0065&#x2c;\\u0020\\u0062&#x75;\\u0074\\u0020\\u006e&#x6f;\\u0074\\u0020\\u0073\\u0069&#x6d;\\u0070&#x6c;\\u0065&#x72;\\u002e\n&#x2d;\\u0020\\u0041&#x6c;\\u0062&#x65;\\u0072\\u0074\\u0020&#x45;\\u0069\\u006e\\u0073&#x74;\\u0065&#x69;\\u006e", "&#x4c;&#x69;\\u0066&#x65;&#x20;&#x69;&#x73;\\u0020&#x72;\\u0065&#x61;&#x6c;\\u006c&#x79;\\u0020\\u0073&#x69;&#x6d;&#x70;\\u006c\\u0065&#x2c;\\u0020\\u0062&#x75;\\u0074\\u0020&#x77;\\u0065\\u0020\\u0069&#x6e;\\u0073\\u0069\\u0073&#x74;\\u0020&#x6f;\\u006e\\u0020\\u006d\\u0061\\u006b\\u0069&#x6e;\\u0067\\u0020&#x69;\\u0074\\u0020\\u0063\\u006f&#x6d;\\u0070\\u006c\\u0069&#x63;\\u0061&#x74;\\u0065&#x64;\\u002e\n&#x2d;&#x20;&#x43;&#x6f;\\u006e&#x66;\\u0075&#x63;&#x69;&#x75;\\u0073", "&#x4f;&#x75;\\u0072&#x20;&#x6c;&#x69;\\u0066&#x65;\\u0020&#x69;\\u0073&#x20;\\u0066\\u0072&#x69;\\u0074\\u0074&#x65;&#x72;\\u0065&#x64;\\u0020\\u0061&#x77;\\u0061\\u0079\\u0020&#x62;\\u0079\\u0020\\u0064\\u0065\\u0074\\u0061\\u0069&#x6c;\\u0020&#x73;&#x69;\\u006d\\u0070\\u006c&#x69;&#x66;&#x79;\\u002c&#x20;\\u0073\\u0069&#x6d;\\u0070\\u006c\\u0069&#x66;\\u0079\\u002e\n\\u002d\\u0020&#x48;\\u0065&#x6e;&#x72;&#x79;\\u0020\\u0044&#x61;&#x76;&#x69;&#x64;&#x20;&#x54;&#x68;\\u006f\\u0072&#x65;\\u0061&#x75;", "&#x54;\\u0068&#x65;&#x20;&#x66;\\u0072&#x65;&#x65;&#x64;\\u006f&#x6d;\\u0020&#x61;&#x6e;\\u0064\\u0020\\u0073\\u0069\\u006d&#x70;\\u006c&#x65;\\u0020&#x62;\\u0065\\u0061\\u0075&#x74;\\u0079\\u0020&#x6f;&#x66;&#x20;\\u0069&#x74;&#x20;&#x69;\\u0073&#x20;\\u0074\\u006f\\u006f&#x20;&#x67;&#x6f;\\u006f&#x64;\\u0020\\u0074&#x6f;\\u0020\\u0070\\u0061\\u0073\\u0073\\u0020&#x75;\\u0070&#x2e;\n&#x2d;\\u0020&#x43;&#x68;&#x72;\\u0069&#x73;&#x74;&#x6f;&#x70;&#x68;\\u0065&#x72;\\u0020\\u004d&#x63;&#x43;\\u0061&#x6e;\\u0064\\u006c\\u0065\\u0073&#x73;", "\\u004e\\u006f&#x74;&#x68;\\u0069\\u006e\\u0067&#x20;&#x69;&#x73;\\u0020\\u006d&#x6f;\\u0072&#x65;\\u0020\\u0073&#x69;\\u006d&#x70;&#x6c;\\u0065\\u0020\\u0074&#x68;\\u0061&#x6e;\\u0020\\u0067&#x72;\\u0065\\u0061&#x74;&#x6e;\\u0065&#x73;\\u0073\\u003b\\u0020\\u0069&#x6e;\\u0064\\u0065\\u0065&#x64;&#x2c;\\u0020\\u0074\\u006f&#x20;\\u0062\\u0065\\u0020&#x73;\\u0069\\u006d\\u0070&#x6c;\\u0065&#x20;&#x69;\\u0073&#x20;&#x74;\\u006f\\u0020&#x62;\\u0065\\u0020\\u0067&#x72;&#x65;\\u0061&#x74;\\u002e\n\\u002d&#x20;&#x52;\\u0061\\u006c&#x70;&#x68;\\u0020&#x57;\\u0061\\u006c&#x64;&#x6f;&#x20;&#x45;\\u006d&#x65;&#x72;&#x73;\\u006f&#x6e;", "&#x53;\\u0069\\u006d&#x70;&#x6c;\\u0065&#x20;&#x63;&#x61;\\u006e\\u0020\\u0062&#x65;&#x20;\\u0068\\u0061&#x72;\\u0064\\u0065\\u0072\\u0020\\u0074&#x68;\\u0061\\u006e\\u0020\\u0063\\u006f\\u006d&#x70;\\u006c\\u0065&#x78;\\u002e\\u0020&#x20;\\u0059&#x6f;&#x75;&#x20;\\u0068&#x61;&#x76;&#x65;\\u0020&#x74;\\u006f\\u0020&#x77;\\u006f&#x72;&#x6b;&#x20;\\u0068&#x61;&#x72;\\u0064\\u0020\\u0074&#x6f;&#x20;&#x67;\\u0065&#x74;\\u0020&#x79;&#x6f;&#x75;&#x72;&#x20;&#x74;&#x68;\\u0069&#x6e;&#x6b;&#x69;&#x6e;\\u0067&#x20;&#x63;\\u006c&#x65;&#x61;&#x6e;&#x20;&#x74;&#x6f;\\u0020&#x6d;\\u0061&#x6b;\\u0065\\u0020&#x69;\\u0074\\u0020&#x73;&#x69;&#x6d;\\u0070\\u006c\\u0065&#x2e;&#x20;\\u0020&#x42;&#x75;&#x74;\\u0020&#x69;&#x74;\\u0027\\u0073&#x20;\\u0077\\u006f&#x72;\\u0074\\u0068&#x20;\\u0069\\u0074\\u0020&#x69;\\u006e&#x20;&#x74;&#x68;\\u0065&#x20;&#x65;\\u006e\\u0064\\u0020\\u0062\\u0065&#x63;\\u0061&#x75;\\u0073&#x65;&#x20;&#x6f;\\u006e\\u0063&#x65;&#x20;&#x79;\\u006f\\u0075&#x20;\\u0067\\u0065\\u0074\\u0020&#x74;&#x68;\\u0065&#x72;&#x65;&#x2c;\\u0020\\u0079&#x6f;&#x75;&#x20;\\u0063\\u0061\\u006e&#x20;\\u006d&#x6f;\\u0076&#x65;\\u0020\\u006d\\u006f&#x75;&#x6e;&#x74;&#x61;\\u0069&#x6e;\\u0073&#x2e;\n&#x2d;\\u0020\\u0053\\u0074&#x65;\\u0076&#x65;&#x20;&#x4a;\\u006f\\u0062&#x73;", "\\u0044&#x6f;&#x20;&#x79;\\u006f&#x75;\\u0020\\u0077\\u0061&#x6e;\\u0074\\u0020&#x74;&#x6f;\\u0020\\u0077&#x6f;\\u0072&#x6b;\\u0020&#x77;&#x69;&#x74;\\u0068\\u0020\\u0075\\u0073\\u0020\\u0061\\u006e\\u0064&#x20;&#x6d;\\u0061\\u006b&#x65;\\u0020&#x74;\\u0068\\u0069\\u006e\\u0067&#x73;\\u0020&#x6c;\\u0069&#x6b;&#x65;\\u0020\\u0074\\u0068\\u0069\\u0073\\u003f\\u0020&#x45;&#x6d;\\u0061&#x69;\\u006c&#x20;\\u0075\\u0073\\u0020\\u0061\\u0074\\u0020&#x73;\\u0075&#x70;&#x70;\\u006f\\u0072\\u0074&#x40;&#x73;&#x69;&#x6d;&#x70;&#x6c;\\u0065\\u006e\\u006f&#x74;&#x65;&#x2e;&#x63;&#x6f;&#x6d;&#x20;\\u0061&#x6e;\\u0064\\u0020\\u006d\\u0065&#x6e;&#x74;\\u0069\\u006f&#x6e;&#x20;&#x74;&#x68;\\u0069\\u0073\\u0020&#x6d;\\u0065&#x73;&#x73;\\u0061&#x67;\\u0065&#x2e;" ] } ```
/content/code_sandbox/Simplenote/Classes/SPAboutViewController.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
6,898
```swift import Foundation // MARK: - IndexPath // extension IndexPath { func transpose(toSection newSection: Int) -> IndexPath { IndexPath(row: row, section: newSection) } } ```
/content/code_sandbox/Simplenote/Classes/IndexPath+Simplenote.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
41
```swift import Foundation import UIKit // MARK: - UIViewController Helpers // extension UIViewController { /// YES! You guessed right! By default, the restorationIdentifier will be the class name /// class var defaultRestorationIdentifier: String { classNameWithoutNamespaces } /// Returns the default nibName: Matches the classname (expressed as a String!) /// class var nibName: String { return classNameWithoutNamespaces } /// Configures the receiver to be presented as a popover from the specified Source View /// func configureAsPopover(barButtonItem: UIBarButtonItem) { modalPresentationStyle = .popover // This will only work in iPad devices! guard let presentationController = popoverPresentationController else { return } presentationController.barButtonItem = barButtonItem presentationController.backgroundColor = .simplenoteNavigationBarModalBackgroundColor } } ```
/content/code_sandbox/Simplenote/Classes/UIViewController+Helpers.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
186
```objective-c // // TWAcitivityOpenInSafari.h // Poster // // 8/17/12. // // #import <UIKit/UIKit.h> @interface SPAcitivitySafari : UIActivity { NSURL *openURL; } @end ```
/content/code_sandbox/Simplenote/Classes/SPAcitivitySafari.h
objective-c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
55
```swift import Foundation // MARK: - SPSquaredButton: Simple convenience UIButton subclass, with a default corner radius // @IBDesignable class SPSquaredButton: UIButton { /// Default Radius /// private let defaultCornerRadius = CGFloat(4) /// Outer Border Radius /// @IBInspectable var cornerRadius: CGFloat { get { return layer.cornerRadius } set { layer.cornerRadius = newValue } } // MARK: - Initializers override init(frame: CGRect) { super.init(frame: frame) setupStyle() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupStyle() } } // MARK: - Private Methods // private extension SPSquaredButton { func setupStyle() { cornerRadius = defaultCornerRadius } } ```
/content/code_sandbox/Simplenote/Classes/SPSquaredButton.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
182
```swift import Foundation // MARK: - UIKeyboardAppearance // extension UIKeyboardAppearance { /// Returns the Keyboard Appearance matching the current Style /// static var simplenoteKeyboardAppearance: UIKeyboardAppearance { SPUserInterface.isDark ? .dark : .default } } ```
/content/code_sandbox/Simplenote/Classes/UIKeyboardAppearance+Simplenote.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
60
```swift // // SPContactsManager.swift // Simplenote // // Created by Jorge Leandro Perez on 12/23/16. // import Foundation import Contacts /// Contacts Helper /// class SPContactsManager: NSObject { /// Checks if we've got permission to access the Contacts Store, or not /// @objc var authorized: Bool { return status == .authorized } /// All of the contacts! /// fileprivate var peopleCache: [PersonTag]? /// Contacts Store Reference /// fileprivate let store = CNContactStore() /// Returns the current Authorization Status /// fileprivate var status: CNAuthorizationStatus { return CNContactStore.authorizationStatus(for: .contacts) } /// Deinitializer /// deinit { NotificationCenter.default.removeObserver(self) } /// Designed Initializer /// override init() { super.init() NotificationCenter.default.addObserver(self, selector: #selector(resetCache), name: .CNContactStoreDidChange, object: nil) } /// Whenever the Auth Status is undetermined, this helper will request access! /// @objc func requestAuthorizationIfNeeded(completion: ((Bool) -> Void)?) { guard status == .notDetermined else { return } store.requestAccess(for: .contacts) { (success, error) in completion?(success) } } /// Returns the subset of Persons that contain a specified keyword, in either their email or name /// @objc func people(with keyword: String) -> [PersonTag] { guard let people = loadPeopleIfNeeded() else { return [] } let normalizedKeyword = keyword.lowercased() return people.filter { person in return person.email.lowercased().contains(normalizedKeyword) || person.name.lowercased().contains(normalizedKeyword) } } } /// Contacts Helper /// private extension SPContactsManager { /// Returns a collection of all of the PersonTag's. /// func loadPeopleIfNeeded() -> [PersonTag]? { guard authorized else { return nil } guard peopleCache == nil else { return peopleCache } peopleCache = loadPeople(with: loadContacts()) return peopleCache } /// Given a collection of Contacts, this helper will return a collection of PersonTag matching instances /// private func loadPeople(with contacts: [CNContact]) -> [PersonTag] { var persons = [PersonTag]() for contact in contacts { let fullname = CNContactFormatter.string(from: contact, style: .fullName) ?? String() for email in contact.emailAddresses { guard let person = PersonTag(name: fullname as String, email: email.value as String) else { continue } persons.append(person) } } return persons } /// Returns a collection of all of the contacts: Only Fullname + Email will be loaded /// private func loadContacts() -> [CNContact] { let keysToFetch = [ CNContactFormatter.descriptorForRequiredKeys(for: .fullName), CNContactEmailAddressesKey as CNKeyDescriptor ] let request = CNContactFetchRequest(keysToFetch: keysToFetch) var contacts = [CNContact]() do { try store.enumerateContacts(with: request) { (contact, _) in contacts.append(contact) } } catch { NSLog("## Error while loading contacts: \(error)") } return contacts } /// Nukes the People Cache. Useful to deal with "Contacts Updated" Notifications /// @objc func resetCache() { peopleCache = nil } } ```
/content/code_sandbox/Simplenote/Classes/SPContactsManager.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
784
```swift import Foundation import UIKit /// UITableViewCell Helpers /// extension UITableViewCell { enum SeparatorWidth { case full case standard } /// Returns a reuseIdentifier that matches the receiver's classname (non namespaced). /// @objc class var reuseIdentifier: String { return classNameWithoutNamespaces } /// Adjust width of a separator /// func adjustSeparatorWidth(width: SeparatorWidth) { var separatorInset = self.separatorInset separatorInset.left = width == .full ? 0 : contentView.layoutMargins.left separatorInset.right = 0 self.separatorInset = separatorInset } } ```
/content/code_sandbox/Simplenote/Classes/UITableViewCell+Simplenote.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
135
```swift import Foundation import UIKit // MARK: - Bundle: Simplenote Methods // extension Bundle { /// Returns the Bundle Short Version String. /// @objc var shortVersionString: String { let version = infoDictionary?[Keys.shortVersionString] as? String return version ?? "" } } extension Bundle { /// Returns the BundleIdentifier /// - Important: /// - When invoked from an App Extension, this API will attempt to determine the "Parent App" Bundle identifier /// - You must also make sure App Extension targets contain the `APP_EXTENSION` constant, in the "active compilation conditions" project settings /// var rootBundleIdentifier: String? { guard isAppExtensionBundle else { return bundleIdentifier } let url = bundleURL.deletingLastPathComponent().deletingLastPathComponent() let rootIdentifier = Bundle(url: url)?.object(forInfoDictionaryKey: kCFBundleIdentifierKey as String) return rootIdentifier as? String } } // MARK: - Private Helpers // private extension Bundle { var isAppExtensionBundle: Bool { #if APP_EXTENSION return true #else return false #endif } } // MARK: - Private Keys // private enum Keys { static let shortVersionString = "CFBundleShortVersionString" } ```
/content/code_sandbox/Simplenote/Classes/Bundle+Simplenote.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
289
```objective-c // // SPTableViewController.m // Simplenote // // Created by Tom Witkin on 10/13/13. // #import "SPTableViewController.h" #import "Simplenote-Swift.h" @implementation SPTableViewController - (void)viewDidLoad { [super viewDidLoad]; [self applyStyle]; } - (void)applyStyle { self.view.backgroundColor = [UIColor simplenoteTableViewBackgroundColor]; self.tableView.backgroundColor = [UIColor clearColor]; self.tableView.separatorColor = [UIColor simplenoteDividerColor]; } #pragma mark - Table view data source - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 0; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return 0; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"]; if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"UITableViewCell"]; cell.backgroundColor = [UIColor simplenoteTableViewCellBackgroundColor]; UIView *selectionView = [[UIView alloc] initWithFrame:cell.bounds]; selectionView.backgroundColor = [UIColor simplenoteLightBlueColor]; cell.selectedBackgroundView = selectionView; cell.textLabel.textColor = [UIColor simplenoteTextColor]; cell.detailTextLabel.textColor = [UIColor simplenoteSecondaryTextColor]; } [self resetCellForReuse:cell]; return cell; } - (void)resetCellForReuse:(UITableViewCell *)cell { cell.textLabel.text = @""; cell.detailTextLabel.text = @""; cell.accessoryView = nil; cell.accessoryType = UITableViewCellAccessoryNone; cell.selectionStyle = UITableViewCellSelectionStyleBlue; } @end ```
/content/code_sandbox/Simplenote/Classes/SPTableViewController.m
objective-c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
375
```objective-c // // NSString+Attributed.h // Simplenote // // Created by Tom Witkin on 9/2/13. // #import <Foundation/Foundation.h> @interface NSString (Attributed) - (NSAttributedString *)attributedString; - (NSMutableAttributedString *)mutableAttributedString; @end ```
/content/code_sandbox/Simplenote/Classes/NSString+Attributed.h
objective-c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
62
```objective-c // // SPRatingsHelper.m // Simplenote // // Created by Jorge Leandro Perez on 3/19/15. // #import "SPRatingsHelper.h" #import "SPAppDelegate.h" #import "SPConstants.h" #import "Settings.h" #import "Simplenote-Swift.h" @implementation SPRatingsHelper - (void)reloadSettings { Simperium *simperium = [[SPAppDelegate sharedDelegate] simperium]; SPBucket *bucket = [simperium bucketForName:NSStringFromClass([Settings class])]; Settings *settings = [bucket objectForKey:[SPCredentials simperiumSettingsObjectKey]]; if (!settings) { return; } SPRatingsHelper *ratings = [SPRatingsHelper sharedInstance]; ratings.ratingsDisabled = settings.ratings_disabled.boolValue; ratings.significantEventsCount = settings.minimum_events.integerValue; ratings.minimumIntervalDays = settings.minimum_interval_days.integerValue; ratings.likeSkipVersions = settings.like_skip_versions.integerValue; ratings.declineSkipVersions = settings.decline_skip_versions.integerValue; ratings.dislikeSkipVersions = settings.dislike_skip_versions.integerValue; } - (BOOL)shouldPromptForAppReview { Simperium *simperium = [[SPAppDelegate sharedDelegate] simperium]; return super.shouldPromptForAppReview && simperium.user.authenticated; } @end ```
/content/code_sandbox/Simplenote/Classes/SPRatingsHelper.m
objective-c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
302
```swift import UIKit // MARK: - PopoverViewController // class PopoverViewController: UIViewController { /// Container view /// @IBOutlet private var containerView: UIView! @IBOutlet private var backgroundView: UIVisualEffectView! @IBOutlet private var shadowView: SPShadowView! /// Layout Constraints for Container View /// @IBOutlet private(set) var containerLeftConstraint: NSLayoutConstraint! @IBOutlet private(set) var containerMaxHeightConstraint: NSLayoutConstraint! /// Setting the following constraints via XIB resulted in weird behaviour /// private(set) var containerTopToTopConstraint: NSLayoutConstraint! private(set) var containerTopToBottomConstraint: NSLayoutConstraint! private let viewController: UIViewController private var passthruView: PassthruView? { return view as? PassthruView } /// Callback is invoked when interacted with passthru view /// var onInteractionWithPassthruView: (() -> Void)? { get { passthruView?.onInteraction } set { passthruView?.onInteraction = newValue } } /// Callback is invoked on view size change /// var onViewSizeChange: (() -> Void)? init(viewController: UIViewController) { self.viewController = viewController super.init(nibName: nil, bundle: nil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Overridden API(s) override func viewDidLoad() { super.viewDidLoad() setupContainerConstraints() setupRootView() setupBackgroundView() setupContainerView() setupShadowView() setupContainerViewController() } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) onViewSizeChange?() } } // MARK: - Initialization // private extension PopoverViewController { func setupContainerConstraints() { containerTopToTopConstraint = containerView.topAnchor.constraint(equalTo: view.topAnchor) containerTopToBottomConstraint = containerView.bottomAnchor.constraint(equalTo: view.topAnchor) containerTopToTopConstraint.isActive = true } func setupRootView() { view.backgroundColor = .clear } func setupBackgroundView() { backgroundView.backgroundColor = .simplenoteAutocompleteBackgroundColor backgroundView.layer.cornerRadius = Metrics.cornerRadius backgroundView.layer.masksToBounds = true } func setupContainerView() { containerView.backgroundColor = .clear containerView.layer.masksToBounds = true containerView.layer.cornerRadius = Metrics.cornerRadius } func setupShadowView() { shadowView.cornerRadius = Metrics.cornerRadius } func setupContainerViewController() { viewController.attach(to: self, attachmentView: .into(containerView)) } } // MARK: - Metrics // private enum Metrics { static let cornerRadius = CGFloat(10) } ```
/content/code_sandbox/Simplenote/Classes/PopoverViewController.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
617
```objective-c // // NSManagedObjectContext+CoreDataExtensions.m // Castaway // // Created by Tom Witkin on 4/5/13. // #import "NSManagedObjectContext+CoreDataExtensions.h" @implementation NSManagedObjectContext (CoreDataExtensions) - (NSArray *)fetchAllObjectsForEntityName:(NSString *)entityName { return [self fetchObjectsForEntityName:entityName withPredicate:nil]; } - (NSArray *)fetchObjectsForEntityName:(NSString *)entityName withPredicate:(NSPredicate *)predicate { NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:entityName inManagedObjectContext:self]; fetchRequest.entity = entity; if (predicate) fetchRequest.predicate = predicate; NSError *error; NSArray *fetchedObjects = [self executeFetchRequest:fetchRequest error:&error]; if (!error && fetchedObjects.count > 0) { return fetchedObjects; } else { return nil; } } - (NSManagedObject *)fetchObjectForEntityName:(NSString *)entityName withPredicate:(NSPredicate *)predicate { NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:entityName inManagedObjectContext:self]; fetchRequest.entity = entity; fetchRequest.fetchLimit = 1; fetchRequest.predicate = predicate; NSError *error; NSArray *fetchedObjects = [self executeFetchRequest:fetchRequest error:&error]; if (!error && fetchedObjects.count > 0) { return fetchedObjects[0]; } else { return nil; } } - (NSManagedObject *)fetchObjectForEntityName:(NSString *)entityName withAttribute:(NSString *)attribute equalTo:(id)equalObject { return [self fetchObjectForEntityName:entityName withPredicate:[NSPredicate predicateWithFormat:@"(%K like %@)", attribute, equalObject]]; } - (NSManagedObject *)fetchObjectForEntityName:(NSString *)entityName withAttributes:(NSArray *)attributes equalToObjects:(NSArray *)equalObjects { if (attributes.count != equalObjects.count) { return nil; } for (NSObject *o in attributes) { if (![NSStringFromClass(o.class) isEqualToString:NSStringFromClass([NSString class])]) { return nil; } } // construct predicate NSMutableArray *predicates = [NSMutableArray array]; for (int i = 0 ; i < attributes.count; i++) { NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(%K like %@)", attributes[i], equalObjects[i]]; [predicates addObject:predicate]; } NSPredicate *compoundPredicate = [NSCompoundPredicate andPredicateWithSubpredicates:predicates]; return [self fetchObjectForEntityName:entityName withPredicate:compoundPredicate]; } - (NSInteger)countObjectsForEntityName:(NSString *)entityName withPredicate:(NSPredicate *)predicate { NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:entityName inManagedObjectContext:self]; fetchRequest.entity = entity; fetchRequest.includesSubentities = NO; //Omit subentities. Default is YES (i.e. include subentities) fetchRequest.predicate = predicate; NSError *error; NSInteger count = [self countForFetchRequest:fetchRequest error:&error]; if (count != NSNotFound) return count; else return 0; } - (void)saveToParent:(void(^)(NSError *error))completion { NSError *error = nil; if (![self save:&error]) { NSLog(@"Unresolved error %@, %@", error, [error userInfo]); if (completion != nil) { completion(error); } } else if (self.parentContext != nil) { [self.parentContext performBlock:^{ [self.parentContext saveToParent:[completion copy]]; }]; } else { if (completion != nil) { completion(nil); } } } @end ```
/content/code_sandbox/Simplenote/Classes/NSManagedObjectContext+CoreDataExtensions.m
objective-c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
902
```swift import Foundation import CoreSpotlight // MARK: - Overridden Methods // extension SPNoteEditorViewController { /// Whenever this instance is removed from its NavigationController, let's cleanup /// override public func willMove(toParent parent: UIViewController?) { super.willMove(toParent: parent) guard parent == nil, self.parent != nil else { return } ensureEmptyNoteIsDeleted() } /// Whenever a ViewController is presented, let's ensure Interlink is dismissed! /// override public func present(_ viewControllerToPresent: UIViewController, animated flag: Bool, completion: (() -> Void)? = nil) { super.present(viewControllerToPresent, animated: flag, completion: completion) interlinkProcessor.dismissInterlinkLookup() } } // MARK: - Interface Initialization // extension SPNoteEditorViewController { /// Sets up the NavigationBar Items /// @objc func configureNavigationBarItems() { actionButton = UIBarButtonItem(image: .image(name: .ellipsisOutlined), style: .plain, target: self, action: #selector(noteOptionsWasPressed(_:))) actionButton.accessibilityIdentifier = "note-menu" actionButton.accessibilityLabel = NSLocalizedString("Menu", comment: "Note Options Button") checklistButton = UIBarButtonItem(image: .image(name: .checklist), style: .plain, target: self, action: #selector(insertChecklistAction(_:))) checklistButton.accessibilityLabel = NSLocalizedString("Inserts a new Checklist Item", comment: "Insert Checklist Button") informationButton = UIBarButtonItem(image: .image(name: .info), style: .plain, target: self, action: #selector(noteInformationWasPressed(_:))) informationButton.accessibilityLabel = NSLocalizedString("Information", comment: "Note Information Button (metrics + references)") createNoteButton = UIBarButtonItem(image: .image(name: .newNote), style: .plain, target: self, action: #selector(handleTapOnCreateNewNoteButton)) createNoteButton.accessibilityLabel = NSLocalizedString("New note", comment: "Label to create a new note") keyboardButton = UIBarButtonItem(image: .image(name: .hideKeyboard), style: .plain, target: self, action: #selector(keyboardButtonAction(_:))) keyboardButton.accessibilityLabel = NSLocalizedString("Dismiss keyboard", comment: "Dismiss Keyboard Button") } /// Sets up the Root ViewController /// @objc func configureRootView() { view.addSubview(noteEditorTextView) view.addSubview(navigationBarBackground) } /// Sets up the Layout /// @objc func configureLayout() { navigationBarBackground.translatesAutoresizingMaskIntoConstraints = false noteEditorTextView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ navigationBarBackground.topAnchor.constraint(equalTo: view.topAnchor), navigationBarBackground.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor), navigationBarBackground.leftAnchor.constraint(equalTo: view.leftAnchor), navigationBarBackground.rightAnchor.constraint(equalTo: view.rightAnchor) ]) NSLayoutConstraint.activate([ noteEditorTextView.topAnchor.constraint(equalTo: view.topAnchor), noteEditorTextView.bottomAnchor.constraint(equalTo: view.bottomAnchor), noteEditorTextView.leftAnchor.constraint(equalTo: view.leftAnchor), noteEditorTextView.rightAnchor.constraint(equalTo: view.rightAnchor) ]) } /// Sets up the Interlinks Processor /// @objc func configureInterlinksProcessor() { interlinkProcessor = InterlinkProcessor(viewContext: SPAppDelegate.shared().managedObjectContext, popoverPresenter: popoverPresenter, parentTextView: noteEditorTextView, excludedEntityID: note.objectID) interlinkProcessor.delegate = self } /// Sets up the Keyboard /// @objc func configureTextViewKeyboard() { noteEditorTextView.keyboardDismissMode = .interactive } /// Sets up text view observers /// @objc func configureTextViewObservers() { noteEditorTextView.onContentPositionChange = { [weak self] in self?.updateTagListPosition() } } private var popoverPresenter: PopoverPresenter { let viewportProvider = { [weak self] () -> CGRect in self?.noteEditorTextView.editingRectInWindow() ?? .zero } return PopoverPresenter(containerViewController: self, viewportProvider: viewportProvider, siblingView: navigationBarBackground) } } // MARK: - Layout // extension SPNoteEditorViewController { open override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() // We need to reset transform to prevent tagView from loosing `safeArea` // We restore transform back in viewDidLayoutSubviews tagView.transform = .identity } open override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() // Adding async here to break a strange layout loop // It happens when add tag field is first responder and device is rotated DispatchQueue.main.async { self.updateTagListPosition() } } } // MARK: - Notifications // extension SPNoteEditorViewController { @objc func startListeningToNotifications() { NotificationCenter.default.addObserver(self, selector: #selector(dismissEditor(_:)), name: NSNotification.Name(rawValue: SPTransitionControllerPopGestureTriggeredNotificationName), object: nil) // voiceover status is tracked because the tag view is anchored // to the bottom of the screen when voiceover is enabled to allow // easier access NotificationCenter.default.addObserver(self, selector: #selector(refreshVoiceOverSupport), name: UIAccessibility.voiceOverStatusDidChangeNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(handleAppDidEnterBackground), name: UIApplication.didEnterBackgroundNotification, object: nil) } @objc private func handleAppDidEnterBackground() { saveScrollPosition() } } // MARK: - Keyboard Handling // extension SPNoteEditorViewController: KeyboardObservable { @objc func startListeningToKeyboardNotifications() { keyboardNotificationTokens = addKeyboardObservers() } @objc func stopListeningToKeyboardNotifications() { guard let tokens = keyboardNotificationTokens else { return } removeKeyboardObservers(with: tokens) keyboardNotificationTokens = nil } public func keyboardWillChangeFrame(beginFrame: CGRect?, endFrame: CGRect?, animationDuration: TimeInterval?, animationCurve: UInt?) { guard let _ = view.window, let endFrame = endFrame, let duration = animationDuration, let curve = animationCurve else { return } updateBottomInsets(keyboardFrame: endFrame, duration: duration, curve: curve) } public func keyboardDidChangeFrame(beginFrame: CGRect?, endFrame: CGRect?, animationDuration: TimeInterval?, animationCurve: UInt?) { guard let _ = view.window, let endFrame = endFrame, let duration = animationDuration, let curve = animationCurve else { return } updateBottomInsets(keyboardFrame: endFrame, duration: duration, curve: curve) } /// Updates the Editor's Bottom Insets /// /// - Note: Floating Keyboard results in `contentInset.bottom = .zero` /// - Note: When the keyboard is visible, we'll substract the `safeAreaInsets.bottom`, since the TextView already considers that gap. /// - Note: We're explicitly turning on / off `enableScrollSmoothening`, since it's proven to be a nightmare when UIAutoscroll is involved. /// private func updateBottomInsets(keyboardFrame: CGRect, duration: TimeInterval, curve: UInt) { let newKeyboardHeight = keyboardFrame.intersection(noteEditorTextView.frame).height let newKeyboardFloats = keyboardFrame.maxY < view.frame.height let newKeyboardIsVisible = newKeyboardHeight != .zero let animationOptions = UIView.AnimationOptions(arrayLiteral: .beginFromCurrentState, .init(rawValue: curve)) let editorBottomInsets = newKeyboardFloats ? .zero : newKeyboardHeight let adjustedBottomInsets = max(editorBottomInsets - view.safeAreaInsets.bottom, .zero) guard noteEditorTextView.contentInset.bottom != adjustedBottomInsets else { return } defer { isKeyboardVisible = newKeyboardIsVisible } self.noteEditorTextView.enableScrollSmoothening = true UIViewPropertyAnimator.runningPropertyAnimator(withDuration: duration, delay: .zero, options: animationOptions, animations: { self.noteEditorTextView.contentInset.bottom = adjustedBottomInsets self.noteEditorTextView.verticalScrollIndicatorInsets.bottom = adjustedBottomInsets self.tagListBottomConstraint.constant = -editorBottomInsets self.view.layoutIfNeeded() }, completion: { _ in self.noteEditorTextView.enableScrollSmoothening = false }) } } // MARK: - Voiceover Support // extension SPNoteEditorViewController { /// Indicates if VoiceOver is running /// private var isVoiceOverEnabled: Bool { UIAccessibility.isVoiceOverRunning } /// Whenver VoiceOver is enabled, this API will lock the Tags List in position /// @objc private func refreshVoiceOverSupport() { updateTagListPosition() } /// Sets behavior for accessibility three finger scroll /// open override func accessibilityScroll(_ direction: UIAccessibilityScrollDirection) -> Bool { switch direction { case .left: presentMarkdownPreview() case .right: navigationController?.popViewController(animated: true) default: // With VoiceOver on, three finger scroll up and down will cause a page up/page down action // If this method returns true that is disabled. Returning false to maintain page up/page down return false } return true } } // MARK: - State Restoration // extension SPNoteEditorViewController { /// NSCoder Keys /// enum CodingKeys: String { case currentNoteKey } private var simperium: Simperium { SPAppDelegate.shared().simperium } open override func encodeRestorableState(with coder: NSCoder) { super.encodeRestorableState(with: coder) // Always make sure the object is persisted before proceeding if note.objectID.isTemporaryID { simperium.save() } coder.encode(note.simperiumKey, forKey: CodingKeys.currentNoteKey.rawValue) } } // MARK: - History // extension SPNoteEditorViewController { /// Indicates if note history is shown on screen /// @objc var isShowingHistory: Bool { return historyViewController != nil } /// Shows note history /// @objc func presentHistoryController() { ensureSearchIsDismissed() save() dimLinksInEditor() let viewController = SPNoteHistoryViewController(note: note, delegate: self) viewController.configureToPresentAsCard(presentationDelegate: self) historyViewController = viewController present(viewController, animated: true) SPTracker.trackEditorVersionsAccessed() } /// Dismiss note history /// @objc(dismissHistoryControllerAnimated:) func dismissHistoryController(animated: Bool) { guard let viewController = historyViewController else { return } cleanUpAfterHistoryDismissal() viewController.dismiss(animated: animated, completion: nil) resetAccessibilityFocus() } private func cleanUpAfterHistoryDismissal() { restoreDefaultLinksDimmingInEditor() historyViewController = nil } } // MARK: - History Delegate // extension SPNoteEditorViewController: SPNoteHistoryControllerDelegate { func noteHistoryControllerDidCancel() { dismissHistoryController(animated: true) restoreOriginalNoteContent() } func noteHistoryControllerDidFinish() { dismissHistoryController(animated: true) modified = true save() } func noteHistoryControllerDidSelectVersion(withContent content: String) { updateEditor(with: content) } } // MARK: - SPCardPresentationControllerDelegate // extension SPNoteEditorViewController: SPCardPresentationControllerDelegate { func cardDidDismiss(_ viewController: UIViewController, reason: SPCardDismissalReason) { cleanUpAfterHistoryDismissal() restoreOriginalNoteContent() } } // MARK: - Information // extension SPNoteEditorViewController { /// Present information controller /// - Parameters: /// - note: Note /// - barButtonItem: Bar button item to be used as a popover target /// @objc func presentInformationController(for note: Note, from barButtonItem: UIBarButtonItem) { let informationViewController = NoteInformationViewController(note: note) let presentAsPopover = UIDevice.sp_isPad() && traitCollection.horizontalSizeClass == .regular if presentAsPopover { let navigationController = SPNavigationController(rootViewController: informationViewController) navigationController.configureAsPopover(barButtonItem: barButtonItem) navigationController.displaysBlurEffect = true self.informationViewController = navigationController present(navigationController, animated: true, completion: nil) } else { dimLinksInEditor() informationViewController.configureToPresentAsCard(onDismissCallback: { [weak self] in self?.restoreDefaultLinksDimmingInEditor() }) self.informationViewController = informationViewController present(informationViewController, animated: true, completion: nil) } } /// Dismiss and present information controller. /// Called when horizontal size class changes /// @objc func updateInformationControllerPresentation() { guard let informationViewController = informationViewController else { return } restoreDefaultLinksDimmingInEditor() informationViewController.dismiss(animated: false) { [weak self] in guard let self = self else { return } self.presentInformationController(for: self.note, from: self.informationButton) } } } // MARK: - Private API(s) // private extension SPNoteEditorViewController { func dismissKeyboardAndSave() { endEditing() save() } func mustBounceMarkdownPreview(note: Note, oldMarkdownState: Bool) -> Bool { note.markdown && oldMarkdownState != note.markdown } func bounceMarkdownPreviewIfNeeded(note: Note, oldMarkdownState: Bool) { guard mustBounceMarkdownPreview(note: note, oldMarkdownState: oldMarkdownState) else { return } bounceMarkdownPreview() } func presentOptionsController(for note: Note, from barButtonItem: UIBarButtonItem) { let optionsViewController = OptionsViewController(note: note) optionsViewController.delegate = self let navigationController = SPNavigationController(rootViewController: optionsViewController) navigationController.configureAsPopover(barButtonItem: barButtonItem) navigationController.displaysBlurEffect = true let oldMarkdownState = note.markdown navigationController.onWillDismiss = { [weak self] in self?.bounceMarkdownPreviewIfNeeded(note: note, oldMarkdownState: oldMarkdownState) } dismissKeyboardAndSave() present(navigationController, animated: true, completion: nil) SPTracker.trackEditorActivitiesAccessed() } func presentShareController(for note: Note, from barButtonItem: UIBarButtonItem) { guard let activityController = UIActivityViewController(note: note) else { return } activityController.configureAsPopover(barButtonItem: barButtonItem) present(activityController, animated: true, completion: nil) SPTracker.trackEditorNoteContentShared() } func presentMarkdownPreview() { guard navigationController?.topViewController == self else { return } let previewViewController = SPMarkdownPreviewViewController() previewViewController.markdownText = noteEditorTextView.plainText navigationController?.pushViewController(previewViewController, animated: true) } } // MARK: - Services // extension SPNoteEditorViewController { func delete(note: Note) { SPTracker.trackEditorNoteDeleted() SPObjectManager.shared().trashNote(note) CSSearchableIndex.default().deleteSearchableNote(note) NoticeController.shared.present(NoticeFactory.noteTrashed(onUndo: { SPObjectManager.shared().restoreNote(note) SPTracker.trackPreformedNoticeAction(ofType: .noteTrashed, noticeType: .undo) })) SPTracker.trackPresentedNotice(ofType: .noteTrashed) } @objc func ensureEmptyNoteIsDeleted() { guard note.isBlank, noteEditorTextView.text.isEmpty else { save() return } SPObjectManager.shared().trashNote(note) } @objc private func handleTapOnCreateNewNoteButton() { saveIfNeeded() if note.isBlank { noteEditorTextView.becomeFirstResponder() return } SPTracker.trackEditorNoteCreated() presentNewNoteReplacingCurrentEditor() } private func presentNewNoteReplacingCurrentEditor() { guard let navigationController = navigationController, let snapshotView = createAndAddEditorSnapshotView() else { return } let viewControllers: [UIViewController] = navigationController.viewControllers.map { if $0 == self { return EditorFactory.shared.build(with: nil) } return $0 } navigationController.setViewControllers(viewControllers, animated: false) UIView.animate(withDuration: 0.2) { snapshotView.transform = .init(translationX: 0, y: snapshotView.frame.height) } completion: { (_) in snapshotView.removeFromSuperview() } } private func createAndAddEditorSnapshotView() -> UIView? { let snapshotRect = CGRect(x: 0, y: noteEditorTextView.adjustedContentInset.top, width: noteEditorTextView.frame.width, height: noteEditorTextView.frame.height - noteEditorTextView.adjustedContentInset.top) guard let snapshotView = view.resizableSnapshotView(from: snapshotRect, afterScreenUpdates: false, withCapInsets: .zero), let navigationController = navigationController else { return nil } snapshotView.frame.origin.y = snapshotRect.origin.y navigationController.view.addSubview(snapshotView) return snapshotView } } // MARK: - Editor // private extension SPNoteEditorViewController { // TODO: Think if we can use it from 'newButtonAction' as well (the animation effect is different) func updateEditor(with content: String, animated: Bool = true) { let contentUpdateBlock = { self.noteEditorTextView.attributedText = NSAttributedString(string: content) self.noteEditorTextView.processChecklists() } guard animated, let snapshot = noteEditorTextView.snapshotView(afterScreenUpdates: false) else { contentUpdateBlock() return } snapshot.frame = noteEditorTextView.frame view.insertSubview(snapshot, aboveSubview: noteEditorTextView) contentUpdateBlock() let animations = { snapshot.alpha = .zero } let completion: (Bool) -> Void = { _ in snapshot.removeFromSuperview() } UIView.animate(withDuration: UIKitConstants.animationShortDuration, animations: animations, completion: completion) } func restoreOriginalNoteContent() { updateEditor(with: note.content) } func dimLinksInEditor() { noteEditorTextView.tintAdjustmentMode = .dimmed } func restoreDefaultLinksDimmingInEditor() { noteEditorTextView.tintAdjustmentMode = .automatic } } // MARK: - OptionsControllerDelegate // extension SPNoteEditorViewController: OptionsControllerDelegate { func optionsControllerDidPressShare(_ sender: OptionsViewController) { sender.dismiss(animated: true, completion: nil) // Wait a bit until the Dismiss Animation concludes. `dismiss(:completion)` takes too long! DispatchQueue.main.asyncAfter(deadline: .now() + UIKitConstants.animationDelayShort) { self.presentShareController(for: sender.note, from: self.actionButton) } } func optionsControllerDidPressHistory(_ sender: OptionsViewController) { sender.dismiss(animated: true, completion: nil) // Wait a bit until the Dismiss Animation concludes. `dismiss(:completion)` takes too long! DispatchQueue.main.asyncAfter(deadline: .now() + UIKitConstants.animationDelayShort) { self.presentHistoryController() } } func optionsControllerDidPressTrash(_ sender: OptionsViewController) { sender.dismiss(animated: true, completion: nil) // Wait a bit until the Dismiss Animation concludes. `dismiss(:completion)` takes too long! DispatchQueue.main.asyncAfter(deadline: .now() + UIKitConstants.animationDelayShort) { self.delete(note: sender.note) self.dismissEditor(sender) } } } // MARK: - Accessibility // private extension SPNoteEditorViewController { func resetAccessibilityFocus() { UIAccessibility.post(notification: .layoutChanged, argument: nil) } } // MARK: - Actions // extension SPNoteEditorViewController { @IBAction func noteOptionsWasPressed(_ sender: UIBarButtonItem) { presentOptionsController(for: note, from: sender) } @objc private func noteInformationWasPressed(_ sender: UIBarButtonItem) { presentInformationController(for: note, from: sender) } } // MARK: - Searching // extension SPNoteEditorViewController { /// Returns ranges of keywords in a given text /// @objc func searchResultRanges(in text: String, withKeywords keywords: [String]) -> [NSRange] { return text.contentSlice(matching: keywords)?.nsMatches ?? [] } } // MARK: - Interlinks // extension SPNoteEditorViewController { /// Dismisses (if needed) and reprocessess Interlink Lookup whenever the current Transition concludes /// @objc(refreshInterlinkLookupWithCoordinator:) func refreshInterlinkLookupWithCoordinator(coordinator: UIViewControllerTransitionCoordinator) { interlinkProcessor.dismissInterlinkLookup() coordinator.animate(alongsideTransition: nil) { _ in self.interlinkProcessor.processInterlinkLookup() } } } // MARK: - InterlinkProcessorDelegate // extension SPNoteEditorViewController: InterlinkProcessorDelegate { func interlinkProcessor(_ processor: InterlinkProcessor, insert text: String, in range: Range<String.Index>) { noteEditorTextView.insertText(text: text, in: range) processor.dismissInterlinkLookup() } } // MARK: - Tags // extension SPNoteEditorViewController { @objc func configureTagListViewController() { let popoverPresenter = self.popoverPresenter popoverPresenter.dismissOnInteractionWithPassthruView = true tagListViewController = NoteEditorTagListViewController(note: note, popoverPresenter: popoverPresenter) addChild(tagListViewController) tagView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(tagView) NSLayoutConstraint.activate([ tagView.leadingAnchor.constraint(equalTo: view.leadingAnchor), tagView.trailingAnchor.constraint(equalTo: view.trailingAnchor) ]) tagListBottomConstraint = tagView.bottomAnchor.constraint(equalTo: view.bottomAnchor) tagListBottomConstraint.isActive = true tagListViewController.didMove(toParent: self) tagListViewController.delegate = self } private func updateTagListPosition() { guard !isVoiceOverEnabled else { tagView.transform = .identity return } let contentHeight = noteEditorTextView.contentSize.height - noteEditorTextView.textContainerInset.bottom + Metrics.additionalTagViewAndEditorCollisionDistance let maxContentY = noteEditorTextView.convert(CGPoint(x: 0, y: contentHeight), to: view).y let tagViewY = tagView.frame.origin.y - tagView.transform.ty let translationY = max(maxContentY - tagViewY, 0) if tagView.transform.ty != translationY { tagView.transform = .init(translationX: 0, y: translationY) } } private var tagView: UIView { return tagListViewController.view } } // MARK: - NoteEditorTagListViewControllerDelegate // extension SPNoteEditorViewController: NoteEditorTagListViewControllerDelegate { func tagListDidUpdate(_ tagList: NoteEditorTagListViewController) { modified = true save() } func tagListIsEditing(_ tagList: NoteEditorTagListViewController) { // Note: When Voiceover is enabled, the Tags Editor is docked! guard !isVoiceOverEnabled else { return } // Without async it doesn't work due to race condition with keyboard frame changes DispatchQueue.main.async { self.noteEditorTextView.scrollToBottom(withAnimation: true) } } } // MARK: - Style // extension SPNoteEditorViewController { @objc func refreshStyle() { refreshRootView() refreshTagsEditor() refreshTextEditor() refreshTextStorage() } private func refreshRootView() { view.backgroundColor = backgroundColor } private func refreshTextEditor() { noteEditorTextView.backgroundColor = backgroundColor noteEditorTextView.keyboardAppearance = .simplenoteKeyboardAppearance noteEditorTextView.checklistsFont = .preferredFont(forTextStyle: .headline) noteEditorTextView.checklistsTintColor = .simplenoteNoteBodyPreviewColor navigationController?.toolbar.isTranslucent = false navigationController?.toolbar.barTintColor = .simplenoteSortBarBackgroundColor } private func refreshTagsEditor() { tagView.backgroundColor = backgroundColor } private func refreshTextStorage() { let headlineFont = UIFont.preferredFont(for: .title1, weight: .bold) let defaultFont = UIFont.preferredFont(forTextStyle: .body) let textColor = UIColor.simplenoteNoteHeadlineColor let lineSpacing = defaultFont.lineHeight * Metrics.lineSpacingMultipler let textStorage = noteEditorTextView.interactiveTextStorage textStorage.defaultStyle = [ .font: defaultFont, .foregroundColor: textColor, .paragraphStyle: NSMutableParagraphStyle(lineSpacing: lineSpacing) ] textStorage.headlineStyle = [ .font: headlineFont, .foregroundColor: textColor, ] } @objc func refreshSearchHighlight() { noteEditorTextView.clearHighlights(false) highlightSearchResult(at: highlightedSearchResultIndex, animated: false) } private var backgroundColor: UIColor { isPreviewing ? .simplenoteBackgroundPreviewColor : .simplenoteBackgroundColor } } // MARK: - Search Map // extension SPNoteEditorViewController { /// Show search map keyword ranges /// // TODO: Use `Range` when `SPNoteEditorViewController` is fully swift @objc func showSearchMap(with searchRangeValues: [NSValue]) { createSearchMapViewIfNeeded() searchMapView?.update(with: searchBarPositions(with: searchRangeValues)) } /// Returns position relative to the total text container height. /// Position value is from 0 to 1 /// private func searchBarPositions(with searchRangeValues: [NSValue]) -> [CGFloat] { let textContainerHeight = textContainerHeightForSearchMap() guard textContainerHeight > CGFloat.leastNormalMagnitude else { return [] } return searchRangeValues.map { let boundingRect = noteEditorTextView.boundingRect(for: $0.rangeValue) return max(boundingRect.midY / textContainerHeight, CGFloat.leastNormalMagnitude) } } private func textContainerHeightForSearchMap() -> CGFloat { var textContainerHeight = noteEditorTextView.layoutManager.usedRect(for: noteEditorTextView.textContainer).size.height textContainerHeight = textContainerHeight + noteEditorTextView.textContainerInset.top + noteEditorTextView.textContainerInset.bottom let textContainerMinHeight = noteEditorTextView.editingRectInWindow().size.height return max(textContainerHeight, textContainerMinHeight) } private func createSearchMapViewIfNeeded() { guard searchMapView == nil else { return } let searchMapView = SearchMapView() view.addSubview(searchMapView) NSLayoutConstraint.activate([ searchMapView.topAnchor.constraint(equalTo: noteEditorTextView.topAnchor, constant: noteEditorTextView.adjustedContentInset.top), searchMapView.bottomAnchor.constraint(equalTo: noteEditorTextView.bottomAnchor, constant: -noteEditorTextView.adjustedContentInset.bottom), searchMapView.trailingAnchor.constraint(equalTo: noteEditorTextView.trailingAnchor), searchMapView.widthAnchor.constraint(equalToConstant: Metrics.searchMapWidth) ]) searchMapView.onSelectionChange = { [weak self] index in self?.highlightSearchResult(at: index, animated: false) } self.searchMapView = searchMapView } /// Hide search map /// @objc func hideSearchMap() { searchMapView?.removeFromSuperview() searchMapView = nil } } // MARK: - Quick Actions // extension SPNoteEditorViewController { @objc func updateHomeScreenQuickActions() { ShortcutsHandler.shared.updateHomeScreenQuickActions(with: note) } } // MARK: - Keyboard // extension SPNoteEditorViewController { open override var canBecomeFirstResponder: Bool { return true } open override var keyCommands: [UIKeyCommand]? { guard presentedViewController == nil else { return nil } var commands = [ UIKeyCommand(input: "n", modifierFlags: [.command], action: #selector(keyboardCreateNewNote), title: Localization.Shortcuts.newNote), ] if note.markdown == true { commands.append(UIKeyCommand(input: "p", modifierFlags: [.command, .shift], action: #selector(keyboardToggleMarkdownPreview), title: Localization.Shortcuts.toggleMarkdown)) } if searching { commands.append(contentsOf: [ UIKeyCommand(input: "g", modifierFlags: [.command], action: #selector(keyboardHighlightNextMatch), title: Localization.Shortcuts.nextMatch), UIKeyCommand(input: "g", modifierFlags: [.command, .shift], action: #selector(keyboardHighlightPrevMatch), title: Localization.Shortcuts.previousMatch), ]) } if noteEditorTextView.isFirstResponder { commands.append(UIKeyCommand(input: "c", modifierFlags: [.command, .shift], action: #selector(keyboardInsertChecklist), title: Localization.Shortcuts.insertChecklist)) } else { commands.append(UIKeyCommand(input: UIKeyCommand.inputTab, modifierFlags: [], action: #selector(keyboardFocusOnEditor))) } commands.append(UIKeyCommand(input: UIKeyCommand.inputReturn, modifierFlags: [.command], action: #selector(keyboardGoBack), title: Localization.Shortcuts.endEditing)) return commands } @objc private func keyboardCreateNewNote() { SPTracker.trackShortcutCreateNote() presentNewNoteReplacingCurrentEditor() } @objc private func keyboardToggleMarkdownPreview() { SPTracker.trackShortcutToggleMarkdownPreview() presentMarkdownPreview() } @objc private func keyboardInsertChecklist() { SPTracker.trackShortcutToggleChecklist() insertChecklistAction(checklistButton) } @objc private func keyboardHighlightNextMatch() { SPTracker.trackShortcutSearchNext() highlightNextSearchResult() } @objc private func keyboardHighlightPrevMatch() { SPTracker.trackShortcutSearchPrev() highlightPrevSearchResult() } @objc private func keyboardFocusOnEditor() { noteEditorTextView.becomeFirstResponder() noteEditorTextView.selectedTextRange = noteEditorTextView.textRange(from: noteEditorTextView.beginningOfDocument, to: noteEditorTextView.beginningOfDocument) } @objc private func keyboardGoBack() { dismissEditor(nil) } } // MARK: - Scroll position // extension SPNoteEditorViewController { @objc func saveScrollPosition() { guard let key = note.simperiumKey else { return } scrollPositionCache.store(position: noteEditorTextView.contentOffset.y, for: key) } @objc func restoreScrollPosition() { guard let key = note.simperiumKey, let offsetY = scrollPositionCache.position(for: key) else { noteEditorTextView.scrollToTop() return } let offset = CGPoint(x: 0, y: offsetY) noteEditorTextView.contentOffset = noteEditorTextView.boundedContentOffset(from: offset) } } // MARK: - Metrics // private enum Metrics { static let lineSpacingMultiplerPad: CGFloat = 0.40 static let lineSpacingMultiplerPhone: CGFloat = 0.20 static var lineSpacingMultipler: CGFloat { UIDevice.isPad ? lineSpacingMultiplerPad : lineSpacingMultiplerPhone } static let searchMapWidth: CGFloat = 15.0 static let additionalTagViewAndEditorCollisionDistance: CGFloat = 16.0 } // MARK: - Localization // private enum Localization { enum Shortcuts { static let newNote = NSLocalizedString("New Note", comment: "Keyboard shortcut: New Note") static let nextMatch = NSLocalizedString("Next Match", comment: "Keyboard shortcut: Note search, Next Match") static let previousMatch = NSLocalizedString("Previous Match", comment: "Keyboard shortcut: Note search, Previous Match") static let insertChecklist = NSLocalizedString("Insert Checklist", comment: "Keyboard shortcut: Insert Checklist") static let toggleMarkdown = NSLocalizedString("Toggle Markdown", comment: "Keyboard shortcut: Toggle Markdown") static let endEditing = NSLocalizedString("End Editing", comment: "Keyboard shortcut: End Editing") } } ```
/content/code_sandbox/Simplenote/Classes/SPNoteEditorViewController+Extensions.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
7,089
```swift import Foundation import UIKit /// Adopters of this protocol will recieve interactive keyboard-based notifications /// by implmenting the provided functions within. /// public protocol KeyboardObservable: AnyObject { /// Called during a Keyboard Repositioning Notification. /// /// - Parameters: /// - beginFrame: starting frame of the keyboard /// - endFrame: ending frame of the keyboard /// - animationDuration: total duration of the keyboard animation /// - animationCurve: animation curve for the keyboard animation /// func keyboardWillChangeFrame(beginFrame: CGRect?, endFrame: CGRect?, animationDuration: TimeInterval?, animationCurve: UInt?) /// Called during an Keyboard Repositioning Notification. /// /// - Parameters: /// - beginFrame: starting frame of the keyboard /// - endFrame: ending frame of the keyboard /// - animationDuration: total duration of the keyboard animation /// - animationCurve: animation curve for the keyboard animation /// func keyboardDidChangeFrame(beginFrame: CGRect?, endFrame: CGRect?, animationDuration: TimeInterval?, animationCurve: UInt?) } /// Interactive Keyboard Observers /// extension KeyboardObservable { /// Setup the keyboard observers for the provided `NotificationCenter`. /// /// - Parameter notificationCenter: `NotificationCenter` to register the keyboard interactive observer /// with (or `.default` if none is specified). /// /// - Returns: An array of opaque objects, strongly retained by the NotificationCenter. Must be passed back to `removeKeyboardObservers` /// public func addKeyboardObservers(to notificationCenter: NotificationCenter = .default) -> [Any] { let tokenWillBegin = notificationCenter.addObserver(forName: UIResponder.keyboardWillChangeFrameNotification, object: nil, queue: nil, using: { [weak self] notification in self?.keyboardWillChangeFrame(beginFrame: notification.keyboardBeginFrame(), endFrame: notification.keyboardEndFrame(), animationDuration: notification.keyboardAnimationDuration(), animationCurve: notification.keyboardAnimationCurve()) }) let tokenDidBegin = notificationCenter.addObserver(forName: UIResponder.keyboardDidChangeFrameNotification, object: nil, queue: nil, using: { [weak self] notification in self?.keyboardDidChangeFrame(beginFrame: notification.keyboardBeginFrame(), endFrame: notification.keyboardEndFrame(), animationDuration: notification.keyboardAnimationDuration(), animationCurve: notification.keyboardAnimationCurve()) }) return [tokenWillBegin, tokenDidBegin] } /// Remove the keyboard observers for the provided `NotificationCenter`. /// /// - Parameter notificationCenter: `NotificationCenter` to remove the keyboard interactive observer /// from (or `.default` if none is specified). /// public func removeKeyboardObservers(with tokens: [Any], from notificationCenter: NotificationCenter = .default) { for token in tokens { notificationCenter.removeObserver(token) } } } // MARK: - Notification + UIKeyboardInfo // private extension Notification { /// Gets the optional CGRect value of the UIKeyboardFrameBeginUserInfoKey from a UIKeyboard notification /// func keyboardBeginFrame () -> CGRect? { return (userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue } /// Gets the optional CGRect value of the UIKeyboardFrameEndUserInfoKey from a UIKeyboard notification /// func keyboardEndFrame () -> CGRect? { return (userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue } /// Gets the optional AnimationDuration value of the UIKeyboardAnimationDurationUserInfoKey from a UIKeyboard notification /// func keyboardAnimationDuration () -> TimeInterval? { return (userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue } /// Gets the optional AnimationCurve value of the UIKeyboardAnimationCurveUserInfoKey from a UIKeyboard notification /// func keyboardAnimationCurve () -> UInt? { return (userInfo?[UIResponder.keyboardAnimationCurveUserInfoKey] as? NSNumber)?.uintValue } } ```
/content/code_sandbox/Simplenote/Classes/KeyboardObservable.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
847
```objective-c // // SPEntryListViewController.m // Simplenote // // Created by Tom Witkin on 8/19/13. // #import "SPEntryListViewController.h" #import "Simplenote-Swift.h" #import "SPEntryListCell.h" #import "SPEntryListAutoCompleteCell.h" static NSString *cellIdentifier = @"primaryCell"; static NSString *autoCompleteCellIdentifier = @"autoCompleteCell"; static CGFloat const EntryListTextFieldSidePadding = 15; static CGFloat const EntryListCellHeight = 44; @implementation SPEntryListViewController - (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self]; } - (void)viewDidLoad { [super viewDidLoad]; [self setupViews]; } - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; [primaryTableView reloadData]; } - (void)setupViews { // setup views CGFloat yOrigin = self.view.safeAreaInsets.top; entryFieldBackground = [[UIView alloc] initWithFrame:CGRectMake(0, yOrigin, self.view.frame.size.width, EntryListCellHeight)]; entryFieldBackground.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleBottomMargin; [self.view addSubview:entryFieldBackground]; entryTextField = [[SPTextField alloc] initWithFrame:CGRectMake(EntryListTextFieldSidePadding, 0, entryFieldBackground.frame.size.width - 2 * EntryListTextFieldSidePadding, entryFieldBackground.frame.size.height)]; entryTextField.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleBottomMargin; entryTextField.keyboardType = UIKeyboardTypeEmailAddress; entryTextField.keyboardAppearance = SPUserInterface.isDark ? UIKeyboardAppearanceDark : UIKeyboardAppearanceDefault; entryTextField.autocapitalizationType = UITextAutocapitalizationTypeNone; entryTextField.delegate = self; [entryFieldBackground addSubview:entryTextField]; entryFieldPlusButton = [UIButton buttonWithType:UIButtonTypeCustom]; UIImage *pickerImage = [UIImage imageWithName:UIImageNameAdd]; [entryFieldPlusButton setImage:pickerImage forState:UIControlStateNormal]; entryFieldPlusButton.frame = CGRectMake(0, 0, pickerImage.size.width, pickerImage.size.height); [entryFieldPlusButton addTarget:self action:@selector(entryFieldPlusButtonTapped:) forControlEvents:UIControlEventTouchUpInside]; entryTextField.rightView = entryFieldPlusButton; entryTextField.rightViewMode = UITextFieldViewModeAlways; primaryTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, yOrigin + entryTextField.frame.size.height, self.view.frame.size.width, self.view.frame.size.height - (yOrigin + entryTextField.frame.size.height)) style:UITableViewStyleGrouped]; primaryTableView.rowHeight = EntryListCellHeight; primaryTableView.delegate = self; primaryTableView.dataSource = self; primaryTableView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth; [self.view addSubview:primaryTableView]; [primaryTableView registerClass:[SPEntryListCell class] forCellReuseIdentifier:cellIdentifier]; [autoCompleteTableView registerClass:[SPEntryListAutoCompleteCell class] forCellReuseIdentifier:autoCompleteCellIdentifier]; // autoCompleteTableView autoCompleteTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, yOrigin + entryTextField.frame.size.height, self.view.frame.size.width, self.view.frame.size.height - (yOrigin + entryTextField.frame.size.height)) style:UITableViewStylePlain]; autoCompleteTableView.delegate = self; autoCompleteTableView.dataSource = self; autoCompleteTableView.hidden = YES; autoCompleteTableView.showsVerticalScrollIndicator = NO; autoCompleteTableView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth; [self.view addSubview:autoCompleteTableView]; // set navigation bar self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(dismiss:)]; [self applyDefaultStyle]; // keyboard notifications // Register for keyboard notifications [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil]; } - (void)applyDefaultStyle { UIColor *backgroundColor = [UIColor simplenoteBackgroundColor]; UIColor *tableBackgroundColor = [UIColor simplenoteTableViewBackgroundColor]; UIColor *tableSeparatorColor = [UIColor simplenoteDividerColor]; // self self.view.backgroundColor = tableBackgroundColor; // entry field entryFieldBackground.backgroundColor = tableBackgroundColor; entryTextField.backgroundColor = [UIColor clearColor]; entryTextField.font = [UIFont preferredFontForTextStyle:UIFontTextStyleBody]; entryTextField.textColor = [UIColor simplenoteTextColor]; entryTextField.placeholdTextColor = [UIColor simplenoteTitleColor]; CALayer *entryFieldBorder = [[CALayer alloc] init]; entryFieldBorder.frame = CGRectMake(0, entryFieldBackground.bounds.size.height - 1.0 / [[UIScreen mainScreen] scale], MAX(self.view.frame.size.width, self.view.frame.size.height), 1.0 / [[UIScreen mainScreen] scale]); entryFieldBorder.backgroundColor = tableSeparatorColor.CGColor; [entryFieldBackground.layer addSublayer:entryFieldBorder]; // tableview primaryTableView.backgroundColor = [UIColor clearColor]; primaryTableView.separatorColor = tableSeparatorColor; autoCompleteTableView.backgroundColor = backgroundColor; autoCompleteTableView.separatorColor = tableSeparatorColor; } - (void)dismiss:(id)sender { [self.navigationController dismissViewControllerAnimated:YES completion:nil]; } - (void)setShowEntryFieldPlusButton:(BOOL)showEntryFieldPlusButton { _showEntryFieldPlusButton = showEntryFieldPlusButton; entryFieldPlusButton.hidden = !_showEntryFieldPlusButton; } - (void)entryFieldPlusButtonTapped:(id)sender { // implemented by a sub-class } #pragma mark UITableViewDataSource Methods - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { if ([tableView isEqual:primaryTableView]) return 0; // this is implemented by subclassing else if ([tableView isEqual:autoCompleteTableView]) return _autoCompleteDataSource.count; return 0; } - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { return nil; } - (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section { return nil; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *finalCell; if ([tableView isEqual:primaryTableView]) { SPEntryListCell *cell = (SPEntryListCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier]; if (!cell) { cell = [[SPEntryListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier]; } finalCell = cell; } else { SPEntryListAutoCompleteCell *cell = (SPEntryListAutoCompleteCell *)[tableView dequeueReusableCellWithIdentifier:autoCompleteCellIdentifier]; if (!cell) { cell = [[SPEntryListAutoCompleteCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:autoCompleteCellIdentifier]; } finalCell = cell;; } finalCell.selectionStyle = UITableViewCellSelectionStyleNone; return finalCell; } - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath { return [tableView isEqual:primaryTableView] ? YES : NO; } - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath { return NO; } - (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath { return UITableViewCellEditingStyleDelete; } - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { if (editingStyle == UITableViewCellEditingStyleDelete) { [self removeItemFromDataSourceAtIndexPath:indexPath]; [primaryTableView beginUpdates]; [primaryTableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft]; [primaryTableView endUpdates]; } } - (void)removeItemFromDataSourceAtIndexPath:(NSIndexPath *)indexPath { [self.dataSource removeObjectAtIndex:indexPath.row]; } #pragma mark UITextFieldDelegate Methods - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { textField.text = [textField.text stringByReplacingCharactersInRange:range withString:string]; // check for matches [self updateAutoCompleteMatchesForString:textField.text]; return NO; } - (BOOL)textFieldShouldReturn:(UITextField *)textField { [self processTextInField]; return NO; } - (void)textFieldDidEndEditing:(UITextField *)textField { // clear auto complete matches autoCompleteTableView.hidden = YES; [self updateAutoCompleteMatchesForString:nil]; } - (void)processTextInField { // to be implemented by a subclass } - (void)updateAutoCompleteMatchesForString:(NSString *)string { // to be implemented by subclasses } - (void)updatedAutoCompleteMatches { autoCompleteTableView.hidden = !(self.autoCompleteDataSource.count > 0); [autoCompleteTableView reloadData]; } #pragma mark UIScrollViewDelegate Methods - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView { if ([scrollView isEqual:primaryTableView]) [entryTextField resignFirstResponder]; } #pragma mark Keyboard - (void)keyboardWillShow:(NSNotification *)notification { CGRect keyboardFrame = [(NSValue *)[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue]; CGFloat keyboardHeight = MIN(keyboardFrame.size.height, keyboardFrame.size.width); CGRect newAutoCompleteFame = autoCompleteTableView.frame; newAutoCompleteFame.size.height = self.view.frame.size.height - newAutoCompleteFame.origin.y - keyboardHeight; UIEdgeInsets contentInset = autoCompleteTableView.contentInset; contentInset.bottom = keyboardHeight; autoCompleteTableView.contentInset = contentInset; } @end ```
/content/code_sandbox/Simplenote/Classes/SPEntryListViewController.m
objective-c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
2,111
```swift import Foundation import UIKit /// UITableViewHeaderFooterView Helpers /// extension UITableViewHeaderFooterView { /// Returns a reuseIdentifier that matches the receiver's classname (non namespaced). /// @objc class var reuseIdentifier: String { return classNameWithoutNamespaces } } ```
/content/code_sandbox/Simplenote/Classes/UITableViewHeaderFooterView+Simplenote.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
60
```swift import Foundation import UIKit // MARK: - SearchDisplayController Delegate Methods // @objc protocol SearchDisplayControllerDelegate: NSObjectProtocol { func searchDisplayControllerShouldBeginSearch(_ controller: SearchDisplayController) -> Bool func searchDisplayController(_ controller: SearchDisplayController, updateSearchResults keyword: String) func searchDisplayControllerWillBeginSearch(_ controller: SearchDisplayController) func searchDisplayControllerDidEndSearch(_ controller: SearchDisplayController) } // MARK: - SearchControllerPresentationContextProvider Methods // @objc protocol SearchControllerPresentationContextProvider: NSObjectProtocol { func navigationControllerForSearchDisplayController(_ controller: SearchDisplayController) -> UINavigationController } // MARK: - Simplenote's Search Controller: Because UIKit's Search Controller is simply unusable // @objcMembers class SearchDisplayController: NSObject { /// Indicates if the SearchController is active (or not!) /// private(set) var active = false /// Internal SearchBar Instance /// let searchBar = SPSearchBar() /// SearchController's Delegate /// weak var delegate: SearchDisplayControllerDelegate? /// SearchController's Presentation Context Provider /// weak var presenter: SearchControllerPresentationContextProvider? /// Designated Initializer /// override init() { super.init() setupSearchBar() } /// Dismissess the SearchBar /// func dismiss() { // Set the inactive status first, and THEN resign the responder. // // Why: Because of the `keyboardWillChangeFrame` Notification. We could really, really use // the actual status to be available when such note is posted. Capisci? // updateStatus(active: false) searchBar.text = nil searchBar.resignFirstResponder() } /// Updates the SearchBar's Text, and notifies the Delegate /// func updateSearchText(searchText: String) { searchBar.text = searchText delegate?.searchDisplayController(self, updateSearchResults: searchText) } /// This method will hide the NavigationBar whenever the SearchDisplayController is in active mode. /// /// We'll rely on this API to ensure transitions from List <> Editor are smooth: In Search Mode the list won't display the NavigationBar, but the /// Editor is always expected to display a navbar. When going backwards, we'll always need to restore the navbar. /// @objc func hideNavigationBarIfNecessary() { updateNavigationBar(hidden: active) } func setEnabled(_ enabled: Bool) { searchBar.isUserInteractionEnabled = enabled searchBar.refreshPlaceholderStyle(searchEnabled: enabled) } } // MARK: - Private Methods // private extension SearchDisplayController { func setupSearchBar() { searchBar.delegate = self searchBar.placeholder = NSLocalizedString("Search", comment: "Search Placeholder") searchBar.searchBarStyle = .minimal searchBar.sizeToFit() } func updateStatus(active: Bool) { guard active != self.active else { return } self.active = active updateSearchBar(showsCancelButton: active) updateNavigationBar(hidden: active) notifyStatusChanged(active: active) } func updateNavigationBar(hidden: Bool) { guard let navigationController = presenter?.navigationControllerForSearchDisplayController(self), navigationController.isNavigationBarHidden != hidden else { return } navigationController.setNavigationBarHidden(hidden, animated: true) UIView.animate(withDuration: TimeInterval(UINavigationController.hideShowBarDuration)) { navigationController.topViewController?.view?.layoutIfNeeded() } } func updateSearchBar(showsCancelButton: Bool) { guard showsCancelButton != searchBar.showsCancelButton else { return } searchBar.setShowsCancelButton(showsCancelButton, animated: true) } func notifyStatusChanged(active: Bool) { if active { delegate?.searchDisplayControllerWillBeginSearch(self) } else { delegate?.searchDisplayControllerDidEndSearch(self) } } } // MARK: - UISearchBar Delegate Methods // extension SearchDisplayController: UISearchBarDelegate { func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool { guard let shouldBeginEditing = delegate?.searchDisplayControllerShouldBeginSearch(self) else { return false } updateStatus(active: shouldBeginEditing) return shouldBeginEditing } func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { delegate?.searchDisplayController(self, updateSearchResults: searchText) } func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { searchBar.resignFirstResponder() } func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { dismiss() } } // MARK: - SPSearchBar // class SPSearchBar: UISearchBar { /// **Custom** Behavior: /// Normally resigning FirstResponder status implies all of the button subviews (ie. cancel button) to become disabled. This implies that /// hiding the keyboard makes it impossible to simply tap `Cancel` to exit **Search Mode**. /// /// With this (relatively safe) workaround, we're keeping any UIButton subview(s) enabled, so that you can just exit Search Mode anytime. /// @discardableResult override func resignFirstResponder() -> Bool { let output = super.resignFirstResponder() for button in subviewsOfType(UIButton.self) { button.isEnabled = true } return output } } ```
/content/code_sandbox/Simplenote/Classes/SearchDisplayController.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
1,143
```objective-c // // SPMarkdownParser.m // Simplenote // // Created by James Frost on 01/10/2015. // #import "SPMarkdownParser.h" #import "html.h" #import "Simplenote-Swift.h" @implementation SPMarkdownParser + (NSString *)renderHTMLFromMarkdownString:(NSString *)markdown { hoedown_renderer *renderer = hoedown_html_renderer_new( HOEDOWN_HTML_SKIP_HTML | HOEDOWN_HTML_USE_TASK_LIST, 0); hoedown_document *document = hoedown_document_new(renderer, HOEDOWN_EXT_AUTOLINK | HOEDOWN_EXT_FENCED_CODE | HOEDOWN_EXT_FOOTNOTES | HOEDOWN_EXT_TABLES, 16, 0, NULL, NULL); hoedown_buffer *html = hoedown_buffer_new(16); NSData *markdownData = [markdown dataUsingEncoding:NSUTF8StringEncoding]; hoedown_document_render(document, html, markdownData.bytes, markdownData.length); NSData *htmlData = [NSData dataWithBytes:html->data length:html->size]; hoedown_buffer_free(html); hoedown_document_free(document); hoedown_html_renderer_free(renderer); NSString *htmlString = [[NSString alloc] initWithData:htmlData encoding:NSUTF8StringEncoding]; return [[[self htmlHeader] stringByAppendingString:htmlString] stringByAppendingString:[self htmlFooter]]; } + (NSString *)htmlHeader { NSString *headerStart = @"<html><head>" "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">" "<link href=\"path_to_url" rel=\"stylesheet\">" "<style media=\"screen\" type=\"text/css\">\n"; NSString *headerEnd = @"</style></head><body><div class=\"note-detail-markdown\">"; NSString *css = [self cssForMarkdown]; return [[headerStart stringByAppendingString:css] stringByAppendingString:headerEnd]; } + (NSString *)cssForMarkdown { NSString *css = [self loadCSSAtPath:self.cssPath]; // Load CSS colors // NSString *colors = [self loadCSSAtPath:self.cssColorPath]; css = [css stringByAppendingString:colors]; // Check if increase contrast is enabled. If enabled amend CSS to include high contrast colors // if ([[UITraitCollection currentTraitCollection] accessibilityContrast] == UIAccessibilityContrastHigh) { NSString *contrast = [self loadCSSAtPath:self.contrastCssPath]; css = [css stringByAppendingString:contrast]; } return css; } + (NSString *)loadCSSAtPath:(NSString *)path { return [NSString stringWithContentsOfURL:[[NSBundle mainBundle] URLForResource:path withExtension:nil] encoding:NSUTF8StringEncoding error:nil]; } + (NSString *)cssPath { return @"markdown-default.css"; } + (NSString *)cssColorPath { if (SPUserInterface.isDark) { return @"markdown-dark.css"; } return @"markdown-light.css"; } + (NSString *)contrastCssPath { if (SPUserInterface.isDark) { return @"markdown-dark-contrast.css"; } return @"markdown-default-contrast.css"; } + (NSString *)htmlFooter { return @"</div></body></html>"; } @end ```
/content/code_sandbox/Simplenote/Classes/SPMarkdownParser.m
objective-c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
717
```swift import Foundation // MARK: - UIScreen Simplenote Methods // extension UIScreen { /// Returns the ratio between 1 point and 1 pixel in the current device. /// @objc var pointToPixelRatio: CGFloat { return 1 / scale } } ```
/content/code_sandbox/Simplenote/Classes/UIScreen+Simplenote.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
61
```swift import Foundation // MARK: - Simplenote Extension // extension DateFormatter { /// Shared DateFormatters /// static let listDateFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateStyle = .short formatter.timeStyle = .none return formatter }() static let dateTimeFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateStyle = .medium formatter.timeStyle = .short return formatter }() static let dateFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateStyle = .medium formatter.timeStyle = .none return formatter }() } ```
/content/code_sandbox/Simplenote/Classes/DateFormatter+Simplenote.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
140
```objective-c #import <Foundation/Foundation.h> #import <Simperium/Simperium.h> #import "Preferences.h" @interface Simperium (Simplenote) - (nonnull Preferences *)preferencesObject; @end ```
/content/code_sandbox/Simplenote/Classes/Simperium+Simplenote.h
objective-c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
43
```swift import UIKit // MARK: - SPNoteHistoryViewController: Shows history for a note // class SPNoteHistoryViewController: UIViewController { @IBOutlet private weak var dateLabel: UILabel! @IBOutlet private weak var errorMessageLabel: UILabel! @IBOutlet private weak var slider: SPSnappingSlider! @IBOutlet private weak var restoreButton: UIButton! @IBOutlet private weak var activityIndicator: UIActivityIndicatorView! @IBOutlet private weak var dismissButton: UIButton! private var transitioningManager: UIViewControllerTransitioningDelegate? private let controller: SPNoteHistoryController /// Designated initializer /// /// - Parameters: /// - controller: business logic controller /// init(controller: SPNoteHistoryController) { self.controller = controller super.init(nibName: nil, bundle: nil) } /// Convenience initializer /// /// - Parameters: /// - note: Note /// - delegate: History delegate /// convenience init(note: Note, delegate: SPNoteHistoryControllerDelegate) { let controller = SPNoteHistoryController(note: note) controller.delegate = delegate self.init(controller: controller) } @available(*, unavailable) required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { stopListeningToNotifications() } override func viewDidLoad() { super.viewDidLoad() refreshStyle() configureSlider() configureAccessibility() startListeningToNotifications() startListeningForControllerChanges() startListeningForSliderValueChanges() controller.onViewLoad() trackScreen() } } // MARK: - Styling // private extension SPNoteHistoryViewController { func refreshStyle() { styleDateLabel() styleErrorMessageLabel() styleSlider() styleRestoreButton() styleActivityIndicator() } func styleDateLabel() { dateLabel.textColor = .simplenoteNoteHeadlineColor } func styleErrorMessageLabel() { errorMessageLabel.textColor = .simplenoteTextColor } func styleSlider() { slider.minimumTrackTintColor = .simplenoteSliderTrackColor slider.maximumTrackTintColor = .simplenoteSliderTrackColor } func styleRestoreButton() { restoreButton.layer.masksToBounds = true restoreButton.setBackgroundImage(UIColor.simplenoteBlue50Color.dynamicImageRepresentation(), for: .normal) restoreButton.setBackgroundImage(UIColor.simplenoteDisabledButtonBackgroundColor.dynamicImageRepresentation(), for: .disabled) restoreButton.setBackgroundImage(UIColor.simplenoteBlue60Color.dynamicImageRepresentation(), for: .highlighted) restoreButton.setTitle(Localization.restoreButtonTitle, for: .normal) } func styleActivityIndicator() { activityIndicator.style = .medium } } // MARK: - Updating UI // private extension SPNoteHistoryViewController { func update(with state: SPNoteHistoryController.State) { switch state { case .version(let versionNumber, let date, let isRestorable): switchToMainContent(isLoading: false) dateLabel.text = date restoreButton.isEnabled = isRestorable updateSlider(withVersionNumber: versionNumber, accessibilityValue: date) case .loadingVersion(let versionNumber): switchToMainContent(isLoading: true) restoreButton.isEnabled = false updateSlider(withVersionNumber: versionNumber, accessibilityValue: Localization.activityIndicatorAccessibilityLabel) case .error(let text): switchToErrorMessage() errorMessageLabel.text = text setAccessibilityFocus(errorMessageLabel) } } func updateSlider(withVersionNumber versionNumber: Int, accessibilityValue: String?) { slider.value = Float(versionNumber) updateSliderAccessibilityValue(accessibilityValue) setAccessibilityFocus(slider) } } // MARK: - Slider // private extension SPNoteHistoryViewController { func startListeningForSliderValueChanges() { slider.onSnappedValueChange = { [weak self] value in self?.controller.select(versionNumber: Int(value)) } } func configureSlider() { let range = controller.versionRange slider.minimumValue = Float(range.lowerBound) slider.maximumValue = Float(range.upperBound) } } // MARK: - Updating content visibility // private extension SPNoteHistoryViewController { func switchToMainContent(isLoading: Bool) { setSliderAndActionButtonVisible(true) setDateVisible(!isLoading) setActivityIndicatorVisible(isLoading) setErrorMessageVisible(false) } func switchToErrorMessage() { setDateVisible(false) setSliderAndActionButtonVisible(false) setActivityIndicatorVisible(false) setErrorMessageVisible(true) } func setDateVisible(_ isVisible: Bool) { // We manipulate alpha to prevent content jumping because of re-layouting dateLabel.alpha = isVisible ? UIKitConstants.alpha1_0 : UIKitConstants.alpha0_0 } func setSliderAndActionButtonVisible(_ isVisible: Bool) { [slider, restoreButton].forEach { $0?.alpha = isVisible ? UIKitConstants.alpha1_0 : UIKitConstants.alpha0_0 } } func setActivityIndicatorVisible(_ isVisible: Bool) { if isVisible { activityIndicator.startAnimating() } else { activityIndicator.stopAnimating() } } func setErrorMessageVisible(_ isVisible: Bool) { errorMessageLabel.isHidden = !isVisible } } // MARK: - Handling button events // private extension SPNoteHistoryViewController { @IBAction func handleTapOnCloseButton() { controller.handleTapOnCloseButton() } @IBAction func handleTapOnRestoreButton() { trackRestore() controller.handleTapOnRestoreButton() } } // MARK: - Controller // private extension SPNoteHistoryViewController { func startListeningForControllerChanges() { controller.observer = { [weak self] state in self?.update(with: state) } } } // MARK: - Theme Notifications // private extension SPNoteHistoryViewController { func startListeningToNotifications() { let nc = NotificationCenter.default nc.addObserver(self, selector: #selector(themeDidChange), name: .SPSimplenoteThemeChanged, object: nil) } func stopListeningToNotifications() { NotificationCenter.default.removeObserver(self) } @objc func themeDidChange() { refreshStyle() } } // MARK: - Tracking // private extension SPNoteHistoryViewController { func trackScreen() { SPTracker.trackEditorVersionsAccessed() } func trackRestore() { SPTracker.trackEditorNoteRestored() } } // MARK: - Accessibility // extension SPNoteHistoryViewController { override func accessibilityPerformEscape() -> Bool { controller.handleTapOnCloseButton() return true } private func setAccessibilityFocus(_ element: UIView) { guard !element.accessibilityElementIsFocused() else { return } UIAccessibility.post(notification: .layoutChanged, argument: element) } private func configureAccessibility() { dismissButton.accessibilityLabel = Localization.dismissAccessibilityLabel slider.accessibilityLabel = Localization.sliderAccessibilityLabel activityIndicator.accessibilityLabel = Localization.activityIndicatorAccessibilityLabel } private func updateSliderAccessibilityValue(_ value: String?) { slider.accessibilityValue = value } } // MARK: - Presentation // extension SPNoteHistoryViewController { /// Configure view controller to be presented as a card /// func configureToPresentAsCard(presentationDelegate: SPCardPresentationControllerDelegate) { let transitioningManager = SPCardTransitioningManager() transitioningManager.presentationDelegate = presentationDelegate self.transitioningManager = transitioningManager transitioningDelegate = transitioningManager modalPresentationStyle = .custom } } // MARK: - SPCardConfigurable // extension SPNoteHistoryViewController: SPCardConfigurable { func shouldBeginSwipeToDismiss(from location: CGPoint) -> Bool { let locationInSlider = slider.convert(location, from: view) // Add an extra padding to the thumb to prevent dismissing from the area around the thumb as well let thumbRect = slider.thumbRect.insetBy(dx: -Constants.sliderThumbPadding, dy: -Constants.sliderThumbPadding) return !thumbRect.contains(locationInSlider) } } // MARK: - Constants // private struct Constants { static let sliderThumbPadding: CGFloat = 15.0 } private struct Localization { static let restoreButtonTitle = NSLocalizedString("Restore Note", comment: "Restore a note to a previous version") static let dismissAccessibilityLabel = NSLocalizedString("Dismiss History", comment: "Accessibility label describing a button used to dismiss a history view of the note") static let sliderAccessibilityLabel = NSLocalizedString("Select a Version", comment: "Accessibility label describing a slider used to reset the current note to a previous version") static let activityIndicatorAccessibilityLabel = NSLocalizedString("Fetching Version", comment: "Accessibility hint used when previous versions of a note are being fetched") } ```
/content/code_sandbox/Simplenote/Classes/SPNoteHistoryViewController.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
1,895
```swift // // SPDefaultTableViewCell.swift // Simplenote // // import Foundation // MARK: - UITableViewCell with the `.default` Style // class SPDefaultTableViewCell: UITableViewCell { /// UITableView's Reusable Identifier /// static let reusableIdentifier = "SPDefaultTableViewCell" /// Designated Initializer /// init() { super.init(style: .default, reuseIdentifier: SPDefaultTableViewCell.reusableIdentifier) applySimplenoteStyle() } /// Required Initializer /// required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) applySimplenoteStyle() } } // MARK: - Private // private extension SPDefaultTableViewCell { func applySimplenoteStyle() { let backgroundView = UIView() backgroundView.backgroundColor = .simplenoteLightBlueColor backgroundColor = .simplenoteTableViewCellBackgroundColor selectedBackgroundView = backgroundView detailTextLabel?.textColor = .simplenoteSecondaryTextColor textLabel?.textColor = .simplenoteTextColor } } ```
/content/code_sandbox/Simplenote/Classes/SPDefaultTableViewCell.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
232
```swift import Foundation // MARK: - Represents all of the possible Sort Modes // @objc enum SortMode: Int, CaseIterable { /// Order: A-Z /// case alphabeticallyAscending /// Order: Z-A /// case alphabeticallyDescending /// Order: Newest on Top /// case createdNewest /// Order: Oldest on Top /// case createdOldest /// Order: Newest on Top /// case modifiedNewest /// Order: Oldest on Top /// case modifiedOldest /// Returns a localized Description, matching the current rawValue /// var description: String { switch self { case .alphabeticallyAscending: return NSLocalizedString("Name: A-Z", comment: "Sort Mode: Alphabetically, ascending") case .alphabeticallyDescending: return NSLocalizedString("Name: Z-A", comment: "Sort Mode: Alphabetically, descending") case .createdNewest: return NSLocalizedString("Created: Newest", comment: "Sort Mode: Creation Date, descending") case .createdOldest: return NSLocalizedString("Created: Oldest", comment: "Sort Mode: Creation Date, ascending") case .modifiedNewest: return NSLocalizedString("Modified: Newest", comment: "Sort Mode: Modified Date, descending") case .modifiedOldest: return NSLocalizedString("Modified: Oldest", comment: "Sort Mode: Modified Date, ascending") } } } ```
/content/code_sandbox/Simplenote/Classes/SortMode.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
315
```swift import Foundation import UIKit // MARK: - UIColor Simplenote's Helpers // extension UIColor { /// Returns an UIImage representation of the receiver, with the specified size, and Dark Mode support. /// func dynamicImageRepresentation(size: CGSize = CGSize(width: 1, height: 1)) -> UIImage { let darkImage = resolvedColor(with: .purelyDarkTraits).imageRepresentation(size: size) let lightImage = resolvedColor(with: .purelyLightTraits).imageRepresentation(size: size) lightImage.imageAsset?.register(darkImage, with: .purelyDarkTraits) return lightImage } /// Returns a rastrerized image of the specified size, representing the receiver instance. /// private func imageRepresentation(size: CGSize) -> UIImage { let rect = CGRect(origin: .zero, size: size) return UIGraphicsImageRenderer(size: size).image { context in self.setFill() context.fill(rect) } } } // MARK: - HTML Colors // extension UIColor { /// Initializes a new UIColor instance with the specified HexString Code. /// convenience init(hexString: String, alpha: CGFloat = 1.0) { let hexString = hexString.trimmingCharacters(in: .whitespacesAndNewlines) let scanner = Scanner(string: hexString) let characters = CharacterSet(charactersIn: "#") scanner.charactersToBeSkipped = .some(characters) var color: UInt64 = 0 scanner.scanHexInt64(&color) let mask = 0x000000FF let r = Int(color >> 16) & mask let g = Int(color >> 8) & mask let b = Int(color) & mask self.init(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: alpha) } } ```
/content/code_sandbox/Simplenote/Classes/UIColor+Helpers.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
419
```swift import Foundation // MARK: - String // extension String { /// Newline /// static let newline = "\n" /// String containing a Space /// static let space = " " /// Tabs /// static let tab = "\t" } // MARK: - Helper API(s) // extension String { /// Returns the Range enclosing all of the receiver's contents /// var fullRange: Range<String.Index> { startIndex ..< endIndex } /// Truncates the receiver's full words, up to a specified maximum length. /// - Note: Whenever this is not possible (ie. the receiver doesn't have words), regular truncation will be performed /// func truncateWords(upTo maximumLength: Int) -> String { var output = String() for word in components(separatedBy: .whitespaces) { if (output.count + word.count) >= maximumLength { break } let prefix = output.isEmpty ? String() : .space output.append(prefix) output.append(word) } if output.isEmpty { return prefix(maximumLength).trimmingCharacters(in: .whitespaces) } return output } /// Returns a new string dropping specified prefix /// func droppingPrefix(_ prefix: String) -> String { guard hasPrefix(prefix) else { return self } return String(dropFirst(prefix.count)) } } // MARK: - Searching for the first / last characters // extension String { /// Find and return the location of the first / last character from the specified character set /// func locationOfFirstCharacter(from searchSet: CharacterSet, startingFrom startLocation: String.Index, backwards: Bool = false) -> String.Index? { rangeOfFirstCharacter(from: searchSet, startingFrom: startLocation, backwards: backwards)?.lowerBound } func rangeOfFirstCharacter(from searchSet: CharacterSet, startingFrom startLocation: String.Index, backwards: Bool = false) -> Range<String.Index>? { guard startLocation <= endIndex else { return nil } let range = backwards ? startIndex..<startLocation : startLocation..<endIndex let characterRange = rangeOfCharacter(from: searchSet, options: backwards ? .backwards : [], range: range) return characterRange } } // MARK: - Searching for keywords // extension String { /// Finds keywords in a string and optionally trims around the first match /// /// - Parameters: /// - keywords: A list of keywords /// - range: Range of the string. If nil full range is used /// - leadingLimit: Limit result string to a certain characters before the first match. Only full words are used. Provide 0 to have no limit. /// - trailingLimit: Limit result string to a certain characters after the first match. Only full words are used. Provide 0 to have no limit. /// func contentSlice(matching keywords: [String], in range: Range<String.Index>? = nil, leadingLimit: Int = 0, trailingLimit: Int = 0) -> ContentSlice? { guard !keywords.isEmpty else { return nil } let range = range ?? startIndex..<endIndex var leadingWordsRange: [Range<String.Index>] = [] var matchingWordsRange: [Range<String.Index>] = [] var trailingWordsRange: [Range<String.Index>] = [] enumerateSubstrings(in: range, options: [.byWords, .localized, .substringNotRequired]) { (_, wordRange, _, stop) in if trailingLimit > 0, let firstMatch = matchingWordsRange.first { if distance(from: firstMatch.upperBound, to: wordRange.upperBound) > trailingLimit { stop = true return } trailingWordsRange.append(wordRange) } for keyword in keywords { if self.range(of: keyword, options: [.caseInsensitive, .diacriticInsensitive], range: wordRange, locale: Locale.current) != nil { matchingWordsRange.append(wordRange) break } } if leadingLimit > 0 && matchingWordsRange.isEmpty { leadingWordsRange.append(wordRange) } } // No matches => return nil guard let firstMatch = matchingWordsRange.first, let lastMatch = matchingWordsRange.last else { return nil } let lowerBound: String.Index = { if leadingLimit == 0 { return range.lowerBound } let upperBound = firstMatch.lowerBound var lowerBound = upperBound for range in leadingWordsRange.reversed() { if distance(from: range.lowerBound, to: upperBound) > leadingLimit { break } lowerBound = range.lowerBound } return lowerBound }() let upperBound: String.Index = { if trailingLimit == 0 { return range.upperBound } return trailingWordsRange.last?.upperBound ?? lastMatch.upperBound }() return ContentSlice(content: self, range: lowerBound..<upperBound, matches: matchingWordsRange) } } // MARK: Substring Instance Count extension String { func occurrences(of string: String) -> Int { return components(separatedBy: string).count - 1 } } // MARK: Simplenote URL Path extension String { static func simplenotePath(withHost host: String? = nil) -> String { let base = SimplenoteConstants.simplenoteScheme + "://" guard let host = host else { return base } return base + host + "/" } } // MARK: Replacing newlines with spaces extension String { func replacingNewlinesWithSpaces() -> String { if isEmpty { return self } var components = self.components(separatedBy: .newlines) components.removeAll { $0.isEmpty } return components.joined(separator: " ") } } ```
/content/code_sandbox/Simplenote/Classes/String+Simplenote.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
1,293
```objective-c // // PersonTag.h // Simplenote // // Created by Michael Johnston on 11-08-23. // #import <Foundation/Foundation.h> @interface PersonTag : NSObject @property (nonatomic, copy) NSString *name; @property (nonatomic, copy) NSString *email; @property (nonatomic) BOOL active; - (instancetype)initWithName:(NSString *)aName email:(NSString *)anEmail; - (NSComparisonResult)compareName:(PersonTag *)anotherTag; - (NSComparisonResult)compareEmail:(PersonTag *)anotherTag; @end ```
/content/code_sandbox/Simplenote/Classes/PersonTag.h
objective-c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
118
```objective-c #import <UIKit/UIKit.h> #import <Simperium/Simperium.h> @class InterlinkProcessor; @class Note; @class SPBlurEffectView; @class SPEditorTextView; @class SPTagView; @class SearchMapView; @class NoteEditorTagListViewController; @class NoteScrollPositionCache; NS_ASSUME_NONNULL_BEGIN @interface SPNoteEditorViewController : UIViewController <SPBucketDelegate> // Navigation Bar @property (nonatomic, strong, readonly) SPBlurEffectView *navigationBarBackground; // Navigation Buttons @property (nonatomic, strong) UIBarButtonItem *actionButton; @property (nonatomic, strong) UIBarButtonItem *checklistButton; @property (nonatomic, strong) UIBarButtonItem *keyboardButton; @property (nonatomic, strong) UIBarButtonItem *createNoteButton; @property (nonatomic, strong) UIBarButtonItem *informationButton; @property (nonatomic, strong, readonly) Note *note; @property (nonatomic, strong) SPEditorTextView *noteEditorTextView; @property (nonatomic, strong) NoteEditorTagListViewController *tagListViewController; @property (nonatomic, strong) NSLayoutConstraint *tagListBottomConstraint; // History @property (nonatomic, weak) UIViewController * _Nullable historyViewController; // Information @property (nonatomic, weak) UIViewController * _Nullable informationViewController; // Interlinks @property (nonatomic, strong) InterlinkProcessor *interlinkProcessor; // Keyboard! @property (nonatomic, strong) NSArray * _Nullable keyboardNotificationTokens; @property (nonatomic) BOOL isKeyboardVisible; @property (nonatomic, strong) SearchMapView * _Nullable searchMapView; // State @property (nonatomic, getter=isEditingNote) BOOL editingNote; @property (nonatomic, getter=isPreviewing) BOOL previewing; @property (nonatomic, assign) BOOL modified; @property (nonatomic, readonly) BOOL searching; @property (nonatomic, assign) NSInteger highlightedSearchResultIndex; @property (nonatomic, strong) NoteScrollPositionCache *scrollPositionCache; - (instancetype)initWithNote:(Note *)note; - (void)dismissEditor:(id _Nullable )sender; - (void)insertChecklistAction:(id _Nullable )sender; - (void)keyboardButtonAction:(id _Nullable )sender; - (void)endEditing; - (void)bounceMarkdownPreview; - (void)ensureSearchIsDismissed; - (void)highlightSearchResultAtIndex:(NSInteger)index animated:(BOOL)animated; - (void)highlightNextSearchResult; - (void)highlightPrevSearchResult; - (void)willReceiveNewContent; - (void)didReceiveNewContent; - (void)didDeleteCurrentNote; - (void)save; - (void)saveIfNeeded; // TODO: We can't use `SearchQuery` as a type here because it doesn't work from swift code (because of SPM) :-( - (void)updateWithSearchQuery:(id _Nullable )query; @end NS_ASSUME_NONNULL_END ```
/content/code_sandbox/Simplenote/Classes/SPNoteEditorViewController.h
objective-c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
580
```objective-c #import "Simplenote-Swift.h" #import "SPTransitionController.h" #import "SPMarkdownPreviewViewController.h" #import "SPInteractivePushPopAnimationController.h" NSString *const SPTransitionControllerPopGestureTriggeredNotificationName = @"SPTransitionControllerPopGestureTriggeredNotificationName"; #pragma mark - Private Properties @interface SPTransitionController () <UIGestureRecognizerDelegate> @property (nonatomic, strong) SPInteractivePushPopAnimationController *pushPopAnimationController; @property (nonatomic, weak) UINavigationController *navigationController; @end @implementation SPTransitionController - (instancetype)initWithNavigationController:(UINavigationController *)navigationController { self = [super init]; if (self) { if ([UIDevice isPad]) { UIPinchGestureRecognizer *pinchGesture = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(handlePinch:)]; [navigationController.view addGestureRecognizer:pinchGesture]; } // Note: // This is required since NoteEditorViewController has a custom TitleView, which causes the // interactivePopGestureRecognizer to stop working on its own! UIGestureRecognizer *interactivePopGestureRecognizer = navigationController.interactivePopGestureRecognizer; [interactivePopGestureRecognizer addTarget:self action:@selector(handlePan:)]; interactivePopGestureRecognizer.delegate = self; self.pushPopAnimationController = [[SPInteractivePushPopAnimationController alloc] initWithNavigationController:navigationController]; self.navigationController = navigationController; } return self; } #pragma mark - UINavigationControllerDelegate - (id<UIViewControllerAnimatedTransitioning>)navigationController:(UINavigationController *)navigationController animationControllerForOperation:(UINavigationControllerOperation)operation fromViewController:(UIViewController *)fromVC toViewController:(UIViewController *)toVC { BOOL navigatingToMarkdownPreview = [fromVC isKindOfClass:[SPMarkdownPreviewViewController class]]; if (!navigatingToMarkdownPreview) { return nil; } self.pushPopAnimationController.navigationOperation = operation; return self.pushPopAnimationController; } - (id<UIViewControllerInteractiveTransitioning>)navigationController:(UINavigationController *)navigationController interactionControllerForAnimationController:(id <UIViewControllerAnimatedTransitioning>) animationController { if (animationController != self.pushPopAnimationController) { return nil; } return self.pushPopAnimationController.interactiveTransition; } #pragma mark - Gesture Recognizers - (void)handlePan:(UIPanGestureRecognizer *)sender { // By the time this method is called, the existing topViewController has been popped // so topViewController contains the view we are transitioning *to*. // We only want to handle the Editor > List transition with a custom transition, so if // there's anything other than the List view on the top of the stack, we'll let the OS handle it. BOOL isTransitioningToList = [self.navigationController.topViewController isKindOfClass:[SPNoteListViewController class]]; if (isTransitioningToList && sender.state == UIGestureRecognizerStateBegan) { [self postPopGestureNotification]; } } - (void)handlePinch:(UIPinchGestureRecognizer*)sender { if (sender.numberOfTouches >= 2 && // require two fingers sender.scale < 1.0 && // pinch in sender.state == UIGestureRecognizerStateBegan) { [self postPopGestureNotification]; } } - (void)postPopGestureNotification { [[NSNotificationCenter defaultCenter] postNotificationName:SPTransitionControllerPopGestureTriggeredNotificationName object:self]; } - (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer { if (gestureRecognizer != self.navigationController.interactivePopGestureRecognizer) { return YES; } BOOL recognizerShouldBegin = self.navigationController.viewControllers.count > 1; if (recognizerShouldBegin) { [self bypassFirstResponderRestorationIfNeeded]; } return recognizerShouldBegin; } - (void)bypassFirstResponderRestorationIfNeeded { UIViewController<SPInteractiveDismissableViewController> *dismissableViewController = (UIViewController<SPInteractiveDismissableViewController> *)self.navigationController.topViewController; if (![dismissableViewController conformsToProtocol:@protocol(SPInteractiveDismissableViewController)]) { return; } if (!dismissableViewController.requiresFirstResponderRestorationBypass) { return; } [dismissableViewController.view endEditing:YES]; } @end ```
/content/code_sandbox/Simplenote/Classes/SPTransitionController.m
objective-c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
892
```swift import Foundation // MARK: - InterlinkProcessorDelegate // protocol InterlinkProcessorDelegate: NSObjectProtocol { /// Invoked whenever an Autocomplete Row has been selected: The handler should insert the specified text at a given range /// func interlinkProcessor(_ processor: InterlinkProcessor, insert text: String, in range: Range<String.Index>) } // MARK: - InterlinkProcessor // class InterlinkProcessor: NSObject { private let viewContext: NSManagedObjectContext private let popoverPresenter: PopoverPresenter private let parentTextView: UITextView private let excludedEntityID: NSManagedObjectID private weak var interlinkViewController: InterlinkViewController? private var lastKnownEditorOffset: CGPoint? private var lastKnownKeywordRange: Range<String.Index>? private var initialEditorOffset: CGPoint? private lazy var resultsController = InterlinkResultsController(viewContext: viewContext) weak var delegate: InterlinkProcessorDelegate? /// Designated Initializer /// init(viewContext: NSManagedObjectContext, popoverPresenter: PopoverPresenter, parentTextView: UITextView, excludedEntityID: NSManagedObjectID) { self.viewContext = viewContext self.popoverPresenter = popoverPresenter self.parentTextView = parentTextView self.excludedEntityID = excludedEntityID } /// Displays the Interlink Lookup UI at the cursor's location when all of the following are **true**: /// /// 1. The Editor isn't Undoing nor Highlighting /// 2. The Editor is the first responder /// 3. There is an interlink `[keyword` at the current location /// 4. There are Notes with `keyword` in their title /// /// Otherwise we'll simply dismiss the Autocomplete View, if any. /// @objc func processInterlinkLookup() { guard mustProcessInterlinkLookup, let (markdownRange, keywordRange, keywordText) = parentTextView.interlinkKeywordAtSelectedLocation, let notes = resultsController.searchNotes(byTitleKeyword: keywordText, excluding: excludedEntityID) else { dismissInterlinkLookup() return } showInterlinkController(with: notes, around: keywordRange) setupInterlinkEventListeners(replacementRange: markdownRange) initialEditorOffset = parentTextView.contentOffset lastKnownEditorOffset = parentTextView.contentOffset lastKnownKeywordRange = keywordRange } /// Dismisses the Interlink UI (if it's onscreen!) /// @objc func dismissInterlinkLookup() { popoverPresenter.dismiss() interlinkViewController = nil } } // MARK: - Presenting // private extension InterlinkProcessor { func showInterlinkController(with notes: [Note], around range: Range<String.Index>) { let keywordFrame = parentTextView.locationInWindowForText(in: range) guard !popoverPresenter.isPresented else { refreshInterlinkController(notes: notes) popoverPresenter.relocate(around: keywordFrame) return } let viewController = InterlinkViewController() interlinkViewController = viewController refreshInterlinkController(notes: notes) popoverPresenter.show(viewController, around: keywordFrame, desiredHeight: viewController.desiredHeight) SPTracker.trackEditorInterlinkAutocompleteViewed() } func refreshInterlinkController(notes: [Note]) { interlinkViewController?.notes = notes } func setupInterlinkEventListeners(replacementRange: Range<String.Index>) { interlinkViewController?.onInsertInterlink = { [weak self] text in guard let self = self else { return } self.delegate?.interlinkProcessor(self, insert: text, in: replacementRange) } } } // MARK: - Scrolling // extension InterlinkProcessor { /// Relocates the Interlink UI (whenever it's visible) to match the new TextView's Content Offset. /// - Important: Whenever the **Maximum Allowed Scroll Offset** is exceeded (and the scroll event is user initiated), we'll just dismiss the UI /// @objc(refreshInterlinkControllerWithNewOffset:isDragging:) func refreshInterlinkController(contentOffset: CGPoint, isDragging: Bool) { defer { lastKnownEditorOffset = contentOffset } guard let oldY = lastKnownEditorOffset?.y, let initialY = initialEditorOffset?.y else { return } popoverPresenter.relocate(by: oldY - contentOffset.y) if isDragging { dismissInterlinkLookupIfNeeded(initialY: initialY, currentY: contentOffset.y) } } /// Dismisses the Interlink Lookup whenever the **Maximum Allowed Scroll Offset** is exceeded /// private func dismissInterlinkLookupIfNeeded(initialY: CGFloat, currentY: CGFloat) { guard abs(currentY - initialY) > Settings.maximumAllowedScrollOffset else { return } dismissInterlinkLookup() } } // MARK: - State // private extension InterlinkProcessor { var mustProcessInterlinkLookup: Bool { let editor = parentTextView return editor.isFirstResponder && !editor.isTextSelected && !editor.isUndoingEditOP } } // MARK: - Settings // private enum Settings { static let maximumAllowedScrollOffset = CGFloat(20) } ```
/content/code_sandbox/Simplenote/Classes/InterlinkProcessor.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
1,148
```swift import Foundation // MARK: - Note // extension Note { /// Indicates if the receiver is a blank document /// @objc var isBlank: Bool { objectID.isTemporaryID && content?.count == .zero && tagsArray?.count == .zero } /// Returns the Creation / Modification date for a given SortMode /// func date(for sortMode: SortMode) -> Date? { switch sortMode { case .alphabeticallyAscending, .alphabeticallyDescending: return nil case .createdNewest, .createdOldest: return creationDate case .modifiedNewest, .modifiedOldest: return modificationDate } } /// Returns the collection user emails with who we're sharing this document /// var emailTags: [String] { guard let tags = tagsArray as? [String] else { return [] } return tags.filter { $0.isValidEmailAddress } } } // MARK: - Previews // extension Note { /// Create title and body previews from content @objc func createPreview() { let noteStructure = NoteContentHelper.structure(of: content) titlePreview = titlePreview(with: noteStructure.title) bodyPreview = bodyPreview(with: noteStructure.trimmedBody) updateTagsArray() } private func titlePreview(with range: Range<String.Index>?) -> String { guard let range = range, let content = content else { return NSLocalizedString("New note...", comment: "Empty Note Placeholder") } let result = String(content[range]) return result.droppingPrefix(Constants.titleMarkdownPrefix) } private func bodyPreview(with range: Range<String.Index>?) -> String? { guard let range = range, let content = content else { return nil } let upperBound = content.index(range.lowerBound, offsetBy: Constants.bodyPreviewCap, limitedBy: range.upperBound) ?? range.upperBound let cappedRange = range.lowerBound..<upperBound return String(content[cappedRange]).replacingNewlinesWithSpaces() } } // MARK: - Excerpt // extension Note { /// Returns excerpt of the content around the first match of one of the keywords /// func bodyExcerpt(keywords: [String]?) -> String? { guard let keywords = keywords, !keywords.isEmpty, let content = content?.precomposedStringWithCanonicalMapping else { return bodyPreview } guard let bodyRange = NoteContentHelper.structure(of: content).trimmedBody else { return nil } guard let excerpt = content.contentSlice(matching: keywords, in: bodyRange, leadingLimit: Constants.excerptLeadingLimit, trailingLimit: Constants.excerptTrailingLimit) else { return bodyPreview } let shouldAddEllipsis = excerpt.range.lowerBound > bodyRange.lowerBound let excerptString = (shouldAddEllipsis ? "" : "") + excerpt.slicedContent return excerptString.replacingNewlinesWithSpaces() } } // MARK: - Constants // private struct Constants { /// Markdown prefix to be removed from title preview /// static let titleMarkdownPrefix = "# " /// Limit for body preview /// static let bodyPreviewCap = 500 /// Leading limit for body excerpt /// static let excerptLeadingLimit = 30 /// Trailing limit for body excerpt static let excerptTrailingLimit = 300 } ```
/content/code_sandbox/Simplenote/Classes/Note+Properties.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
747
```swift import Foundation import UIKit // MARK: - NSMutableAttributedString Methods // extension NSMutableAttributedString { /// Returns the (foundation) associated NSString /// var foundationString: NSString { string as NSString } /// Appends a given String with the specified Foreground Color /// func append(string: String, foregroundColor: UIColor? = nil) { var attributes = [NSAttributedString.Key: Any]() if let foregroundColor = foregroundColor { attributes[.foregroundColor] = foregroundColor } let suffix = NSAttributedString(string: string, attributes: attributes) append(suffix) } /// Applies a given UIColor instance to substrings matching a given Keyword /// func apply(color: UIColor, toSubstringsMatching keywords: [String]) { guard let excerpt = string.contentSlice(matching: keywords) else { return } for range in excerpt.nsMatches { addAttribute(.foregroundColor, value: color, range: range) } } /// Create an attributed string highlighting a term /// convenience init(string text: String, attributes: [NSAttributedString.Key: Any], highlighting term: String, highlightAttributes: [NSAttributedString.Key: Any]) { self.init(string: text, attributes: attributes) if let range = text.range(of: term) { addAttributes(highlightAttributes, range: NSRange(range, in: text)) } } } ```
/content/code_sandbox/Simplenote/Classes/NSMutableAttributedString+Simplenote.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
295
```swift import Foundation import UIKit // MARK: - SPPlaceholderView // @objc class SPPlaceholderView: UIView { /// DisplayMode: Defines the way in which the Placeholder behaves /// enum DisplayMode { case generic case pictureAndText(imageName: UIImageName, text: String) case text(text: String, actionText: String, actionHandler: () -> Void) } /// Placeholder's Display Mode /// var displayMode: DisplayMode = .generic { didSet { displayModeWasChanged() } } /// Placeholder Image /// private lazy var imageView: UIImageView = { let imageView = UIImageView() imageView.alpha = Constants.imageViewAlpha imageView.contentMode = .scaleAspectFit return imageView }() /// Placeholder TextLabel /// private lazy var textLabel: UILabel = { let label = UILabel() label.textAlignment = .center label.numberOfLines = Constants.numberOfLines label.font = .preferredFont(forTextStyle: .body) return label }() /// Placeholder ActionLabel /// private lazy var actionLabel: UILabel = { let label = UILabel() label.textAlignment = .center label.numberOfLines = Constants.numberOfLines label.font = .preferredFont(forTextStyle: .body) return label }() /// Internal StackView /// private lazy var stackView: UIStackView = { let stackView = UIStackView(arrangedSubviews: [imageView, textLabel, actionLabel]) stackView.axis = .vertical return stackView }() // MARK: - Initializers init() { super.init(frame: .zero) configureSubviews() setupGestureRecognizer() startListeningToNotifications() } required init?(coder: NSCoder) { super.init(coder: coder) configureSubviews() setupGestureRecognizer() startListeningToNotifications() } deinit { stopListeningToNotifications() } } // MARK: - Private Methods // private extension SPPlaceholderView { func configureSubviews() { imageView.heightAnchor.constraint(equalToConstant: Constants.imageViewHeight).isActive = true addFillingSubview(stackView) refreshStyle() } func refreshStyle() { imageView.tintColor = .simplenotePlaceholderImageColor actionLabel.textColor = .simplenoteBlue50Color textLabel.textColor = .simplenotePlaceholderTextColor switch displayMode { case .text: textLabel.font = .preferredFont(forTextStyle: .title3) stackView.spacing = Constants.stackViewCondensedSpacing default: textLabel.font = .preferredFont(forTextStyle: .body) stackView.spacing = Constants.stackViewDefaultSpacing } } func displayModeWasChanged() { switch displayMode { case .generic: imageView.image = .image(name: .simplenoteLogo) textLabel.text = nil actionLabel.text = nil case .pictureAndText(let imageName, let text): imageView.image = .image(name: imageName) textLabel.text = text actionLabel.text = nil case .text(let text, let action, _): imageView.image = nil textLabel.text = text actionLabel.text = action } imageView.isHidden = imageView.image == nil textLabel.isHidden = textLabel.text == nil actionLabel.isHidden = actionLabel.text == nil refreshStyle() } func setupGestureRecognizer() { addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleTap))) } @objc func handleTap() { guard case DisplayMode.text(_, _, let actionHandler) = displayMode else { return } actionHandler() } } // MARK: - Theme // private extension SPPlaceholderView { func startListeningToNotifications() { let nc = NotificationCenter.default nc.addObserver(self, selector: #selector(themeDidChange), name: .SPSimplenoteThemeChanged, object: nil) } func stopListeningToNotifications() { NotificationCenter.default.removeObserver(self) } @objc func themeDidChange() { refreshStyle() } } // MARK: - Constants // private enum Constants { static let imageViewAlpha = CGFloat(0.5) static let imageViewHeight = CGFloat(72) static let numberOfLines = 0 static let stackViewDefaultSpacing = CGFloat(25) static let stackViewCondensedSpacing = CGFloat(5) } ```
/content/code_sandbox/Simplenote/Classes/SPPlaceholderView.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
963
```objective-c #import "SPNoteEditorViewController.h" #import "Note.h" #import "SPAppDelegate.h" #import "SPNoteListViewController.h" #import "SPEditorTextView.h" #import "SPObjectManager.h" #import "SPAddCollaboratorsViewController.h" #import "JSONKit+Simplenote.h" #import "UITextView+Simplenote.h" #import "SPObjectManager.h" #import "SPInteractiveTextStorage.h" #import "SPTracker.h" #import "NSString+Bullets.h" #import "SPTransitionController.h" #import "SPTextView.h" #import "NSString+Attributed.h" #import "SPAcitivitySafari.h" #import "SPNavigationController.h" #import "SPMarkdownPreviewViewController.h" #import "SPInteractivePushPopAnimationController.h" #import "Simplenote-Swift.h" #import "SPConstants.h" @import SafariServices; @import SimplenoteSearch; CGFloat const SPSelectedAreaPadding = 20; @interface SPNoteEditorViewController ()<SPEditorTextViewDelegate, SPInteractivePushViewControllerProvider, SPInteractiveDismissableViewController, UIActionSheetDelegate, UIPopoverPresentationControllerDelegate> // UIKit Components @property (nonatomic, strong) SPBlurEffectView *navigationBarBackground; @property (nonatomic, strong) UILabel *searchDetailLabel; @property (nonatomic, strong) UIBarButtonItem *nextSearchButton; @property (nonatomic, strong) UIBarButtonItem *prevSearchButton; @property (nonatomic, strong) UIBarButtonItem *doneSearchButton; // Timers @property (nonatomic, strong) NSTimer *saveTimer; @property (nonatomic, strong) NSTimer *guarenteedSaveTimer; // State @property (nonatomic, assign) BOOL searching; @property (nonatomic, assign) BOOL viewingVersions; // Remote Updates @property (nonatomic, assign) NSUInteger cursorLocationBeforeRemoteUpdate; @property (nonatomic, strong) NSString *noteContentBeforeRemoteUpdate; // Versions @property (nonatomic, assign) NSInteger currentVersion; @property (nonatomic, strong) NSMutableDictionary *noteVersionData; // Search @property (nonatomic, strong) NSArray *searchResultRanges; @property (nonatomic, strong) SearchQuery *searchQuery; @end @implementation SPNoteEditorViewController - (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self]; } - (instancetype _Nonnull)initWithNote:(Note * _Nonnull)note { self = [super init]; if (self) { _note = note; } return self; } - (void)configureTextView { _noteEditorTextView = [[SPEditorTextView alloc] init]; _noteEditorTextView.delegate = self; _noteEditorTextView.dataDetectorTypes = UIDataDetectorTypeAll; _noteEditorTextView.font = [UIFont preferredFontForTextStyle:UIFontTextStyleBody]; _noteEditorTextView.checklistsFont = [UIFont preferredFontForTextStyle:UIFontTextStyleHeadline]; } - (void)viewDidLoad { [super viewDidLoad]; self.navigationItem.title = nil; // Editor [self configureTextView]; [self configureNavigationBarItems]; [self configureNavigationBarBackground]; [self configureNavigationControllerToolbar]; [self configureRootView]; [self configureLayout]; [self configureTagListViewController]; [self configureInterlinksProcessor]; [self configureTextViewKeyboard]; [self startListeningToNotifications]; [self startListeningToThemeNotifications]; [self refreshStyle]; [self configureTextViewObservers]; [self displayNote]; } - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; [self highlightSearchResultsIfNeeded]; [self configureNavigationController]; [self startListeningToKeyboardNotifications]; [self refreshNavigationBarButtons]; // Async here to make sure all the frames are correct dispatch_async(dispatch_get_main_queue(), ^{ [self restoreScrollPosition]; }); } - (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; self.userActivity = [NSUserActivity openNoteActivityFor:self.note]; [self ensureEditorIsFirstResponder]; } - (void)configureNavigationBarBackground { NSAssert(self.navigationBarBackground == nil, @"NavigationBarBackground was already initialized!"); self.navigationBarBackground = [SPBlurEffectView navigationBarBlurView]; } - (void)configureNavigationController { // Note: Our navigationBar *may* be hidden, as per SPSearchController in the Notes List [self.navigationController setNavigationBarHidden:NO animated:YES]; [self.navigationController setToolbarHidden:!self.searching animated:YES]; } - (void)ensureEditorIsFirstResponder { if ((self.note.content.length == 0) && !self.isShowingHistory && !self.isPreviewing) { [_noteEditorTextView becomeFirstResponder]; } } - (void)startListeningToThemeNotifications { NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; [nc addObserver:self selector:@selector(themeDidChange) name:SPSimplenoteThemeChangedNotification object:nil]; } - (void)themeDidChange { [self save]; [self.noteEditorTextView endEditing:YES]; [self refreshStyle]; } - (void)highlightSearchResultsIfNeeded { if (!self.searching || !self.searchQuery || self.searchQuery.isEmpty || self.searchResultRanges) { return; } NSString *searchText = _noteEditorTextView.text; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{ self.searchResultRanges = [self searchResultRangesIn:(searchText ?: @"") withKeywords:self.searchQuery.keywords]; dispatch_async(dispatch_get_main_queue(), ^{ [self showSearchMapWith:self.searchResultRanges]; UIColor *tintColor = [UIColor simplenoteEditorSearchHighlightColor]; [self.noteEditorTextView.textStorage applyBackgroundColor:tintColor toRanges:self.searchResultRanges]; NSInteger count = self.searchResultRanges.count; NSString *searchDetailFormat = count == 1 ? NSLocalizedString(@"%d Result", @"Number of found search results") : NSLocalizedString(@"%d Results", @"Number of found search results"); self.searchDetailLabel.text = [NSString stringWithFormat:searchDetailFormat, count]; self.searchDetailLabel.alpha = UIKitConstants.alpha0_0; [UIView animateWithDuration:0.3 animations:^{ self.searchDetailLabel.alpha = UIKitConstants.alpha1_0; }]; [self highlightSearchResultAtIndex:0 animated:YES]; }); }); } - (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; [self saveScrollPosition]; } - (void)viewDidDisappear:(BOOL)animated { [super viewDidDisappear:animated]; [self stopListeningToKeyboardNotifications]; } - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator { [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator]; [self refreshTagEditorOffsetWithCoordinator:coordinator]; [self refreshInterlinkLookupWithCoordinator:coordinator]; [self refreshSearchHighlightIfNeededWithCoordinator:coordinator]; } - (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection { [super traitCollectionDidChange:previousTraitCollection]; if (self.traitCollection.horizontalSizeClass != previousTraitCollection.horizontalSizeClass) { [self updateInformationControllerPresentation]; } if (self.traitCollection.userInterfaceStyle == previousTraitCollection.userInterfaceStyle) { return; } // Okay. Let's talk. // Whenever `applyStyle` gets called whenever this VC is not really onScreen, it might have issues with SPUserInteface.isDark // (since the active traits might not really match the UIWindow's traits). // // For the above reason, we _must_ listen to Trait Change events, and refresh the style appropriately. // // Ref. path_to_url // [self refreshStyle]; } - (void)refreshTagEditorOffsetWithCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator { if (!self.tagListViewController.isFirstResponder) { return; } [coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> _Nonnull context) { [self.tagListViewController scrollEntryFieldToVisibleAnimated:NO]; } completion:nil]; } - (void)refreshSearchHighlightIfNeededWithCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator { if (!self.searching) { return; } [coordinator animateAlongsideTransitionInView:nil animation:^(id<UIViewControllerTransitionCoordinatorContext> _Nonnull context) { [self refreshSearchHighlight]; } completion:nil]; } - (void)configureSearchToolbar { UIImage *chevronRightImage = [UIImage imageWithName:UIImageNameChevronRight]; UIImage *chevronLeftImage = [UIImage imageWithName:UIImageNameChevronLeft]; self.doneSearchButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(endSearching:)]; self.doneSearchButton.width += 10.0; UIBarButtonItem *flexibleSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil]; UIBarButtonItem *flexibleSpaceTwo = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil]; self.nextSearchButton = [[UIBarButtonItem alloc] initWithImage:chevronRightImage style:UIBarButtonItemStylePlain target:self action:@selector(highlightNextSearchResult)]; self.nextSearchButton.width = 34.0; self.prevSearchButton = [[UIBarButtonItem alloc] initWithImage:chevronLeftImage style:UIBarButtonItemStylePlain target:self action:@selector(highlightPrevSearchResult)]; self.prevSearchButton.width = 34.0; self.searchDetailLabel = [[UILabel alloc] init]; self.searchDetailLabel.font = [UIFont preferredFontForTextStyle:UIFontTextStyleBody]; self.searchDetailLabel.frame = CGRectMake(0, 0, 180, self.searchDetailLabel.font.lineHeight); self.searchDetailLabel.textColor = [UIColor simplenoteNoteHeadlineColor]; self.searchDetailLabel.textAlignment = NSTextAlignmentCenter; self.searchDetailLabel.alpha = 0.0; UIBarButtonItem *detailButton = [[UIBarButtonItem alloc] initWithCustomView:self.searchDetailLabel]; [self setToolbarItems:@[self.doneSearchButton, flexibleSpace, detailButton, flexibleSpaceTwo, self.prevSearchButton, self.nextSearchButton] animated:NO]; } - (void)configureNavigationControllerToolbar { if (self.searching) { [self configureSearchToolbar]; } } - (void)ensureNoteIsVisibleInList { // TODO: This should definitely be handled by the Note List itself. Please! // This code is only called in limited amount of cases. It is not called when you press back button in the nav bar. // Do we need this code? :thinking: SPNoteListViewController *listController = [[SPAppDelegate sharedDelegate] noteListViewController]; NSIndexPath *notePath = [listController.notesListController indexPathForObject:self.note]; if (notePath && ![[listController.tableView indexPathsForVisibleRows] containsObject:notePath]) [listController.tableView scrollToRowAtIndexPath:notePath atScrollPosition:UITableViewScrollPositionTop animated:NO]; } - (void)dismissEditor:(id)sender { if ([self isShowingHistory]) { return; } [self endEditing]; [self ensureEmptyNoteIsDeleted]; [self ensureNoteIsVisibleInList]; [self.presentedViewController dismissViewControllerAnimated:YES completion:nil]; [self.navigationController popToRootViewControllerAnimated:YES]; } - (void)displayNote { [self.noteEditorTextView scrollToTop]; // Synchronously set the TextView's contents. Otherwise we risk race conditions with `highlightSearchResults` self.noteEditorTextView.attributedText = [self.note.content attributedString]; // Push off Checklist Processing to smoothen out push animation dispatch_async(dispatch_get_main_queue(), ^{ [self.noteEditorTextView processChecklists]; }); // mark note as read self.note.unread = NO; self.modified = NO; self.previewing = NO; [self updateHomeScreenQuickActions]; } - (void)endEditing { [self.view endEditing:YES]; } // Bounces a snapshot of the text view to hint to the user how to access // the Markdown preview. - (void)bounceMarkdownPreview { UIView *snapshot = [self.noteEditorTextView snapshotViewAfterScreenUpdates:YES]; [self.view insertSubview:snapshot aboveSubview:self.noteEditorTextView]; // We want to hint that there's some content on the right. Creating an actual // SPMarkdownPreviewViewController is fairly expensive, so we'll fake it by // using the plain text content and dimming it out. UIView *fakeMarkdownPreviewSnapshot = [self.noteEditorTextView snapshotViewAfterScreenUpdates:YES]; fakeMarkdownPreviewSnapshot.alpha = 0.3; [snapshot addSubview:fakeMarkdownPreviewSnapshot]; // Offset the fake markdown preview off to the right of the screen bool isLTR = [UIView userInterfaceLayoutDirectionForSemanticContentAttribute: self.view.semanticContentAttribute] == UIUserInterfaceLayoutDirectionLeftToRight; int multiplier = isLTR ? 1 : -1; CGRect frame = snapshot.frame; frame.origin.x = CGRectGetWidth(self.view.bounds) * multiplier; fakeMarkdownPreviewSnapshot.frame = frame; self.noteEditorTextView.hidden = YES; CGFloat bounceDistance = -40 * multiplier; // Do a nice bounce animation [UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{ snapshot.transform = CGAffineTransformMakeTranslation(bounceDistance, 0); } completion:^(BOOL finished) { [UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionCurveEaseIn animations:^{ snapshot.transform = CGAffineTransformIdentity; } completion:^(BOOL finished) { [UIView animateWithDuration:0.2 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{ snapshot.transform = CGAffineTransformMakeTranslation(bounceDistance/2, 0); } completion:^(BOOL finished) { [UIView animateWithDuration:0.2 delay:0 options:UIViewAnimationOptionCurveEaseIn animations:^{ snapshot.transform = CGAffineTransformIdentity; } completion:^(BOOL finished) { self.noteEditorTextView.hidden = NO; [snapshot removeFromSuperview]; }]; }]; }]; }]; } - (void)refreshNavigationBarButtons { NSMutableArray *buttons = [NSMutableArray array]; if (self.shouldHideKeyboardButton) { [buttons addObject:self.createNoteButton]; } else { [buttons addObject:self.keyboardButton]; } [buttons addObject:self.actionButton]; [buttons addObject:self.informationButton]; if (self.isEditingNote) { [buttons addObject:self.checklistButton]; } self.navigationItem.rightBarButtonItems = buttons; } - (BOOL)shouldHideKeyboardButton { if ([UIDevice isPad]) { return YES; } return !self.isKeyboardVisible; } #pragma mark - Property Accessors - (void)setEditingNote:(BOOL)editingNote { _editingNote = editingNote; [self refreshNavigationBarButtons]; } - (void)setIsKeyboardVisible:(BOOL)isKeyboardVisible { _isKeyboardVisible = isKeyboardVisible; [self refreshNavigationBarButtons]; } - (void)setPreviewing:(BOOL)previewing { _previewing = previewing; [self refreshStyle]; } #pragma mark - UIPopoverPresentationControllerDelegate // The activity sheet breaks when transitioning from a popover to a modal-style // presentation, so we'll tell it not to change its presentation if the // view's size class changes. - (UIModalPresentationStyle)adaptivePresentationStyleForPresentationController:(UIPresentationController *)controller { return UIModalPresentationNone; } #pragma mark - SPInteractivePushViewControllerProvider (Markdown Preview) - (UIViewController *)nextViewControllerForInteractivePush { SPMarkdownPreviewViewController *previewViewController = [SPMarkdownPreviewViewController new]; previewViewController.markdownText = [self.noteEditorTextView plainText]; return previewViewController; } - (BOOL)interactivePushPopAnimationControllerShouldBeginPush:(SPInteractivePushPopAnimationController *)controller touchPoint:(CGPoint)touchPoint { if (!self.note.markdown) { return NO; } if (!self.noteEditorTextView.isTextSelected) { return YES; } // We'll check if the Push Gesture intersects with the Selected Text's bounds. If so, we'll deny the // Push Interaction. CGRect selectedSquare = CGRectInset(self.noteEditorTextView.selectedBounds, -SPSelectedAreaPadding, -SPSelectedAreaPadding); CGPoint convertedPoint = [self.view convertPoint:touchPoint toView:self.noteEditorTextView]; return !CGRectContainsPoint(selectedSquare, convertedPoint); } - (void)interactivePushPopAnimationControllerWillBeginPush:(SPInteractivePushPopAnimationController *)controller { // This dispatch is to prevent the animations executed when ending editing // from happening interactively along with the push on iOS 9. dispatch_async(dispatch_get_main_queue(), ^{ [self.tagListViewController.view endEditing:YES]; }); } #pragma mark - SPInteractiveDismissableViewController - (BOOL)requiresFirstResponderRestorationBypass { // Whenever an Interactive Dismiss OP kicks off, we're requesting the "First Responder Restoration" mechanism // to be overridden. // Ref. path_to_url return YES; } #pragma mark search - (void)updateWithSearchQuery:(SearchQuery *)searchQuery { if (!searchQuery || searchQuery.isEmpty) { return; } self.searching = YES; _searchQuery = searchQuery; self.searchResultRanges = nil; [self.navigationController setToolbarHidden:NO animated:YES]; } - (void)highlightNextSearchResult { [self highlightSearchResultAtIndex:(self.highlightedSearchResultIndex + 1) animated:YES]; } - (void)highlightPrevSearchResult { [self highlightSearchResultAtIndex:(self.highlightedSearchResultIndex - 1) animated:YES]; } - (void)highlightSearchResultAtIndex:(NSInteger)index animated:(BOOL)animated { NSInteger searchResultCount = self.searchResultRanges.count; if (searchResultCount < 1) { return; } index = MIN(index, searchResultCount - 1); index = MAX(index, 0); self.highlightedSearchResultIndex = index; // enable or disbale search result puttons accordingly self.prevSearchButton.enabled = index > 0; self.nextSearchButton.enabled = index < searchResultCount - 1; NSRange targetRange = [(NSValue *)self.searchResultRanges[index] rangeValue]; [_noteEditorTextView highlightRange:targetRange animated:YES withBlock:^(CGRect highlightFrame) { [self.noteEditorTextView scrollRectToVisible:highlightFrame animated:animated]; }]; } - (void)endSearching:(id)sender { [self hideSearchMap]; if ([sender isEqual:self.doneSearchButton]) [[SPAppDelegate sharedDelegate].noteListViewController endSearching]; _noteEditorTextView.text = [_noteEditorTextView plainText]; [_noteEditorTextView processChecklists]; _searchQuery = nil; self.searchResultRanges = nil; [_noteEditorTextView clearHighlights:(sender ? YES : NO)]; self.searching = NO; [self configureNavigationController]; [self configureNavigationControllerToolbar]; self.searchDetailLabel.text = nil; } - (void)ensureSearchIsDismissed { if (self.searching) { [self endSearching:_noteEditorTextView]; } } #pragma mark UIScrollViewDelegate methods - (void)scrollViewDidScroll:(UIScrollView *)scrollView { // Slowly Fade-In the NavigationBar's Blur [self.navigationBarBackground adjustAlphaMatchingContentOffsetOf:scrollView]; // Relocate Interlink Suggestions (if they're even onscreen!) [self.interlinkProcessor refreshInterlinkControllerWithNewOffset:scrollView.contentOffset isDragging:scrollView.isDragging]; } #pragma mark UITextViewDelegate methods // only called for user changes // safe to alter text attributes here - (BOOL)textViewShouldBeginEditing:(UITextView *)textView { if ([self isShowingHistory]) { return NO; } [self ensureSearchIsDismissed]; return YES; } - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text { BOOL appliedAutoBullets = [textView applyAutoBulletsWithReplacementText:text replacementRange:range]; return !appliedAutoBullets; } - (BOOL)textView:(UITextView *)textView shouldInteractWithTextAttachment:(NSTextAttachment *)textAttachment inRange:(NSRange)characterRange interaction:(UITextItemInteraction)interaction { // Don't allow "3d press" on our checkbox images return NO; } - (void)textViewDidChange:(UITextView *)textView { self.modified = YES; [self.saveTimer invalidate]; self.saveTimer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(saveAndSync:) userInfo:nil repeats:NO]; self.saveTimer.tolerance = 0.1; if (!self.guarenteedSaveTimer) { self.guarenteedSaveTimer = [NSTimer scheduledTimerWithTimeInterval:21.0 target:self selector:@selector(saveAndSync:) userInfo:nil repeats:NO]; self.guarenteedSaveTimer.tolerance = 1.0; } if([textView.text hasSuffix:@"\n"] && _noteEditorTextView.selectedRange.location == _noteEditorTextView.text.length) { double delayInSeconds = 0.1; dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC)); dispatch_after(popTime, dispatch_get_main_queue(), ^(void){ CGPoint bottomOffset = CGPointMake(0, self.noteEditorTextView.contentSize.height - self.noteEditorTextView.bounds.size.height); if (self.noteEditorTextView.contentOffset.y < bottomOffset.y) [self.noteEditorTextView setContentOffset:bottomOffset animated:YES]; }); } [_noteEditorTextView processChecklists]; [self.interlinkProcessor processInterlinkLookup]; // Ensure we get back to capitalizing sentences instead of Words after autobulleting. // See UITextView+Simplenote if (_noteEditorTextView.autocapitalizationType != UITextAutocapitalizationTypeSentences) { _noteEditorTextView.autocapitalizationType = UITextAutocapitalizationTypeSentences; [_noteEditorTextView reloadInputViews]; } } - (void)textViewDidBeginEditing:(UITextView *)textView { self.editingNote = YES; } - (void)textViewDidEndEditing:(UITextView *)textView { self.editingNote = NO; [self.interlinkProcessor dismissInterlinkLookup]; [self cancelSaveTimers]; [self save]; } - (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange interaction:(UITextItemInteraction)interaction { // When `performsAggressiveLinkWorkaround` is true we'll get link interactions via `receivedInteractionWithURL:` if (URL.containsHttpScheme && !_noteEditorTextView.performsAggressiveLinkWorkaround) { [self presentSafariViewControllerAtURL:URL]; return NO; } if (URL.isSimplenoteURL) { [[UIApplication sharedApplication] openURL:URL options:@{} completionHandler:nil]; return NO; } return YES; } - (void)textView:(UITextView *)textView receivedInteractionWithURL:(NSURL *)url { /// This API is expected to only be called in iOS (13.0.x, 13.1.x) [self presentSafariViewControllerAtURL:url]; } - (void)textViewDidChangeSelection:(UITextView *)textView { if (self.noteEditorTextView.isInserting || self.noteEditorTextView.isDeletingBackward) { return; } [self.interlinkProcessor dismissInterlinkLookup]; } #pragma mark - SafariViewController Methods - (void)presentSafariViewControllerAtURL:(NSURL *)url { SFSafariViewController *sfvc = [[SFSafariViewController alloc] initWithURL:url]; [self presentViewController:sfvc animated:YES completion:nil]; } - (BOOL)isDictatingText { NSString *inputMethod = _noteEditorTextView.textInputMode.primaryLanguage; if (inputMethod != nil) { return [inputMethod isEqualToString:@"dictation"]; } return NO; } #pragma mark Simperium - (void)cancelSaveTimers { [self.saveTimer invalidate]; self.saveTimer = nil; [self.guarenteedSaveTimer invalidate]; self.guarenteedSaveTimer = nil; } - (void)saveAndSync:(NSTimer *)timer { [self save]; [self cancelSaveTimers]; } - (void)saveIfNeeded { if (self.modified == NO) { return; } [self save]; } - (void)save { if (self.isShowingHistory || [self isDictatingText]) { return; } if (self.modified || self.note.deleted == YES) { // Update note self.note.content = [_noteEditorTextView plainText]; self.note.modificationDate = [NSDate date]; // Force an update of the note's content preview in case only tags changed [self.note createPreview]; // Simperum: save [[SPAppDelegate sharedDelegate] save]; [SPTracker trackEditorNoteEdited]; [[CSSearchableIndex defaultSearchableIndex] indexSearchableNote:self.note]; self.modified = NO; [self updateHomeScreenQuickActions]; } } - (void)willReceiveNewContent { self.cursorLocationBeforeRemoteUpdate = [_noteEditorTextView selectedRange].location; self.noteContentBeforeRemoteUpdate = [_noteEditorTextView plainText]; if (![_noteEditorTextView.text isEqualToString:@""]) { self.note.content = [_noteEditorTextView plainText]; [[SPAppDelegate sharedDelegate].simperium saveWithoutSyncing]; } } - (void)didReceiveNewContent { NSUInteger newLocation = [self newCursorLocation:self.note.content oldText:self.noteContentBeforeRemoteUpdate currentLocation:self.cursorLocationBeforeRemoteUpdate]; _noteEditorTextView.attributedText = [self.note.content attributedString]; [_noteEditorTextView processChecklists]; NSRange newRange = NSMakeRange(newLocation, 0); [_noteEditorTextView setSelectedRange:newRange]; [_tagListViewController reload]; } - (void)didDeleteCurrentNote { NSString *title = NSLocalizedString(@"This note was deleted on another device", @"Warning message shown when current note is deleted on another device"); NSString *cancelTitle = NSLocalizedString(@"Accept", @"Label of accept button on alert dialog"); UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:nil preferredStyle:UIAlertControllerStyleAlert]; [alertController addCancelActionWithTitle:cancelTitle handler:^(UIAlertAction *action) { [self endSearching:nil]; [self dismissEditor:nil]; }]; [alertController presentFromRootViewController]; } #pragma mark barButton action methods - (void)keyboardButtonAction:(id)sender { [self endEditing]; [self.tagListViewController.view endEditing:YES]; } - (void)insertChecklistAction:(id)sender { [_noteEditorTextView insertOrRemoveChecklist]; [SPTracker trackEditorChecklistInserted]; } - (NSUInteger)newCursorLocation:(NSString *)newText oldText:(NSString *)oldText currentLocation:(NSUInteger)location { NSUInteger newCursorLocation = location; // Cases: // 0. All text after cursor (and possibly more) was removed ==> put cursor at end // 1. Text was added after the cursor ==> no change // 2. Text was added before the cursor ==> location advances // 3. Text was removed after the cursor ==> no change // 4. Text was removed before the cursor ==> location retreats // 5. Text was added/removed on both sides of the cursor ==> not handled NSInteger deltaLength = newText.length - oldText.length; // Case 0 if (newText.length < location) return newText.length; BOOL beforeCursorMatches = NO; BOOL afterCursorMatches = NO; @try { beforeCursorMatches = [[oldText substringToIndex:location] compare:[newText substringToIndex:location]] == NSOrderedSame; afterCursorMatches = [[oldText substringFromIndex:location] compare:[newText substringFromIndex:location+deltaLength]] == NSOrderedSame; } @catch (NSException *e) { } // Cases 2 and 4 if (!beforeCursorMatches && afterCursorMatches) { newCursorLocation += deltaLength; } // Cases 1, 3 and 5 have no change return newCursorLocation; } @end ```
/content/code_sandbox/Simplenote/Classes/SPNoteEditorViewController.m
objective-c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
6,270
```swift import Foundation import UIKit // MARK: - Simplenote Methods // extension UIContextualAction { /// Initializes a Contextual Action with the specified parameters /// convenience init(style: UIContextualAction.Style, title: String? = nil, image: UIImage? = nil, backgroundColor: UIColor, handler: @escaping UIContextualAction.Handler) { self.init(style: style, title: title, handler: handler) self.image = image self.backgroundColor = backgroundColor } } ```
/content/code_sandbox/Simplenote/Classes/UIContextualAction+Simplenote.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
111
```objective-c // // SPEditorTextView.m // Simplenote // // Created by Tom Witkin on 8/16/13. // #import "SPEditorTextView.h" #import "SPInteractiveTextStorage.h" #import "NSMutableAttributedString+Styling.h" #import "Simplenote-Swift.h" NSString *const MarkdownUnchecked = @"- [ ]"; NSString *const MarkdownChecked = @"- [x]"; NSString *const TextAttachmentCharacterCode = @"\U0000fffc"; // Represents the glyph of an NSTextAttachment static CGFloat const TextViewContanerInsetsTop = 8; static CGFloat const TextViewContanerInsetsBottom = 88; // TODO: Drop this the second SplitViewController is implemented static CGFloat const TextViewRegularByRegularPadding = 64; static CGFloat const TextViewDefaultPadding = 20; // TODO: Drop this the second SplitViewController is implemented static CGFloat const TextViewMaximumWidthPad = 640; static CGFloat const TextViewMaximumWidthPhone = 0; // One unicode character plus a space NSInteger const ChecklistCursorAdjustment = 2; @interface SPEditorTextView ()<UIGestureRecognizerDelegate> @property (strong, nonatomic) SPEditorTapRecognizerDelegate *internalRecognizerDelegate; @property (strong, nonatomic) NSArray *textCommands; @property (nonatomic) UITextLayoutDirection verticalMoveDirection; @property (nonatomic) CGRect verticalMoveStartCaretRect; @property (nonatomic) CGRect verticalMoveLastCaretRect; @property (nonatomic) BOOL isInserting; @property (nonatomic) BOOL isDeletingBackward; @end @implementation SPEditorTextView - (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self]; } - (instancetype)init { self = [super init]; if (self) { self.alwaysBounceHorizontal = NO; self.alwaysBounceVertical = YES; self.scrollEnabled = YES; self.verticalMoveStartCaretRect = CGRectZero; self.verticalMoveLastCaretRect = CGRectZero; [self setupTextContainerInsets]; [self setupGestureRecognizers]; [self startListeningToNotifications]; // Why: Data Detectors simply don't work if `isEditable = YES` [self setEditable:NO]; } return self; } - (void)setupTextContainerInsets { UIEdgeInsets containerInsets = self.textContainerInset; containerInsets.top += TextViewContanerInsetsTop; containerInsets.bottom += TextViewContanerInsetsBottom; self.textContainerInset = containerInsets; } - (void)setupGestureRecognizers { SPEditorTapRecognizerDelegate *recognizerDelegate = [SPEditorTapRecognizerDelegate new]; recognizerDelegate.parentTextView = self; self.internalRecognizerDelegate = recognizerDelegate; UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onTextTapped:)]; tapGestureRecognizer.cancelsTouchesInView = NO; tapGestureRecognizer.delegate = recognizerDelegate; [self addGestureRecognizer:tapGestureRecognizer]; } - (void)startListeningToNotifications { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didEndEditing:) name:UITextViewTextDidEndEditingNotification object:nil]; } - (NSDictionary *)typingAttributes { return self.text.length == 0 ? self.interactiveTextStorage.headlineStyle : self.interactiveTextStorage.defaultStyle; } // TODO: Drop this the second SplitViewController is implemented - (CGFloat)horizontalPadding { return [UIDevice isPad] && !self.isHorizontallyCompact ? TextViewRegularByRegularPadding : TextViewDefaultPadding; } // TODO: Drop this the second SplitViewController is implemented - (CGFloat)maximumWidth { return [UIDevice isPad] ? TextViewMaximumWidthPad : TextViewMaximumWidthPhone; } - (void)layoutSubviews { [super layoutSubviews]; CGFloat padding = self.horizontalPadding; padding += self.safeAreaInsets.left; CGFloat maxWidth = self.maximumWidth; CGFloat width = self.bounds.size.width; if (width - 2 * padding > maxWidth && maxWidth > 0) { padding = (width - maxWidth) * 0.5; } self.textContainer.lineFragmentPadding = padding; } - (BOOL)becomeFirstResponder { // Editable status is true by default but we fiddle with it during setup. self.editable = YES; return [super becomeFirstResponder]; } - (void)insertText:(NSString *)text { self.isInserting = YES; [super insertText:text]; self.isInserting = NO; } - (void)deleteBackward { self.isDeletingBackward = YES; [super deleteBackward]; self.isDeletingBackward = NO; } - (BOOL)resignFirstResponder { // TODO: Only invalidate when resigning. // This can be called multiple times while updating the responder chain. // Ideally, we'd only invalidate the layout when the call to super is successful. BOOL response = [super resignFirstResponder]; [self setNeedsLayout]; return response; } - (void)scrollToBottomWithAnimation:(BOOL)animated { /// Notes: /// - We consider `adjusted bottom inset` because that's how we inject the Tags Editor padding! /// - And we don't consider `adjusted top insets` since that deals with navbar overlaps, and doesn't affect our calculations. CGFloat visibleHeight = self.bounds.size.height - self.textContainerInset.top - self.textContainerInset.bottom - self.contentInset.bottom; if (self.contentSize.height <= visibleHeight) { return; } CGFloat yOffset = self.contentSize.height + self.adjustedContentInset.bottom - self.bounds.size.height; if (self.contentOffset.y == yOffset) { return; } CGPoint scrollOffset = CGPointMake(0, yOffset); [self setContentOffset:scrollOffset animated:animated]; } - (void)scrollToTop { CGFloat yOffset = self.bounds.origin.y - self.contentInset.top; CGPoint scrollOffset = CGPointMake(0, yOffset); [self setContentOffset:scrollOffset animated:NO]; } #pragma mark - Notifications - (void)didEndEditing:(NSNotification *)notification { [self setEditable:NO]; } - (void)scrollRangeToVisible:(NSRange)range { [super scrollRangeToVisible:range]; if (self.layoutManager.extraLineFragmentTextContainer != nil && self.selectedRange.location == range.location) { CGRect caretRect = [self caretRectForPosition:self.selectedTextRange.start]; [self scrollRectToVisible:caretRect animated:YES]; } } // From path_to_url #pragma mark Keyboard Commands - (NSArray *)keyCommands { if (!self.textCommands) { UIKeyCommand *upCommand = [UIKeyCommand keyCommandWithInput:UIKeyInputUpArrow modifierFlags:0 action:@selector(moveUp:)]; UIKeyCommand *downCommand = [UIKeyCommand keyCommandWithInput:UIKeyInputDownArrow modifierFlags:0 action:@selector(moveDown:)]; self.textCommands = @[upCommand, downCommand]; } return self.textCommands; } - (BOOL)canPerformAction:(SEL)action withSender:(id)sender { if (action == @selector(moveUp:) || action == @selector(moveDown:)) { return YES; } return [super canPerformAction:action withSender:sender]; } #pragma mark - - (void)moveUp:(id)sender { UITextPosition *p0 = self.selectedTextRange.start; if ([self isNewVerticalMovementForPosition:p0 inDirection:UITextLayoutDirectionUp]) { self.verticalMoveDirection = UITextLayoutDirectionUp; self.verticalMoveStartCaretRect = [self caretRectForPosition:p0]; } if (p0) { UITextPosition *p1 = [self closestPositionToPosition:p0 inDirection:UITextLayoutDirectionUp]; if (p1) { self.verticalMoveLastCaretRect = [self caretRectForPosition:p1]; UITextRange *r = [self textRangeFromPosition:p1 toPosition:p1]; self.selectedTextRange = r; } } } - (void)moveDown:(id)sender { UITextPosition *p0 = self.selectedTextRange.end; if ([self isNewVerticalMovementForPosition:p0 inDirection:UITextLayoutDirectionDown]) { self.verticalMoveDirection = UITextLayoutDirectionDown; self.verticalMoveStartCaretRect = [self caretRectForPosition:p0]; } if (p0) { UITextPosition *p1 = [self closestPositionToPosition:p0 inDirection:UITextLayoutDirectionDown]; if (p1) { self.verticalMoveLastCaretRect = [self caretRectForPosition:p1]; UITextRange* r = [self textRangeFromPosition:p1 toPosition:p1]; self.selectedTextRange = r; } } } - (UITextPosition *)closestPositionToPosition:(UITextPosition *)position inDirection:(UITextLayoutDirection)direction { // Currently only up and down are implemented. NSParameterAssert(direction == UITextLayoutDirectionUp || direction == UITextLayoutDirectionDown); // Translate the vertical direction to a horizontal direction. UITextLayoutDirection lookupDirection = (direction == UITextLayoutDirectionUp) ? UITextLayoutDirectionLeft : UITextLayoutDirectionRight; // Walk one character at a time in `lookupDirection` until the next line is reached. UITextPosition *checkPosition = position; UITextPosition *closestPosition = position; CGRect startingCaretRect = [self caretRectForPosition:position]; CGRect nextLineCaretRect; BOOL isInNextLine = NO; while (YES) { UITextPosition *nextPosition = [self positionFromPosition:checkPosition inDirection:lookupDirection offset:1]; if (!nextPosition || [self comparePosition:checkPosition toPosition:nextPosition] == NSOrderedSame) { // End of line. break; } checkPosition = nextPosition; CGRect checkRect = [self caretRectForPosition:checkPosition]; if (CGRectGetMidY(startingCaretRect) != CGRectGetMidY(checkRect)) { // While on the next line stop just above/below the starting position. if (lookupDirection == UITextLayoutDirectionLeft && CGRectGetMidX(checkRect) <= CGRectGetMidX(self.verticalMoveStartCaretRect)) { closestPosition = checkPosition; break; } if (lookupDirection == UITextLayoutDirectionRight && CGRectGetMidX(checkRect) >= CGRectGetMidX(self.verticalMoveStartCaretRect)) { closestPosition = checkPosition; break; } // But don't skip lines. if (isInNextLine && CGRectGetMidY(checkRect) != CGRectGetMidY(nextLineCaretRect)) { break; } isInNextLine = YES; nextLineCaretRect = checkRect; closestPosition = checkPosition; } } return closestPosition; } - (BOOL)isNewVerticalMovementForPosition:(UITextPosition *)position inDirection:(UITextLayoutDirection)direction { CGRect caretRect = [self caretRectForPosition:position]; BOOL noPreviousStartPosition = CGRectEqualToRect(self.verticalMoveStartCaretRect, CGRectZero); BOOL caretMovedSinceLastPosition = !CGRectEqualToRect(caretRect, self.verticalMoveLastCaretRect); BOOL directionChanged = self.verticalMoveDirection != direction; BOOL newMovement = noPreviousStartPosition || caretMovedSinceLastPosition || directionChanged; return newMovement; } #pragma mark - Checklists - (void)processChecklists { if (self.attributedText.length == 0) { return; } [self.textStorage processChecklistsWithColor:self.checklistsTintColor sizingFont:self.checklistsFont allowsMultiplePerLine:NO]; } - (void)insertOrRemoveChecklist { NSRange lineRange = [self.text lineRangeForRange:self.selectedRange]; NSUInteger cursorPosition = self.selectedRange.location; NSUInteger selectionLength = self.selectedRange.length; // Check if cursor is at a checkbox, if so we won't adjust cursor position BOOL cursorIsAtCheckbox = NO; if (self.text.length >= self.selectedRange.location + 1) { NSString *characterAtCursor = [self.text substringWithRange:NSMakeRange(self.selectedRange.location, 1)]; cursorIsAtCheckbox = [characterAtCursor isEqualToString:TextAttachmentCharacterCode]; } NSString *lineString = [self.text substringWithRange:lineRange]; BOOL didInsertCheckbox = NO; NSString *resultString = @""; int addedCheckboxCount = 0; if ([lineString containsString:TextAttachmentCharacterCode] && [lineString length] >= ChecklistCursorAdjustment) { // Remove the checkboxes in the selection NSString *codeAndSpace = [TextAttachmentCharacterCode stringByAppendingString:@" "]; resultString = [lineString stringByReplacingOccurrencesOfString:codeAndSpace withString:@""]; } else { // Add checkboxes to the selection NSString *checkboxString = [MarkdownUnchecked stringByAppendingString:@" "]; NSArray *stringLines = [lineString componentsSeparatedByString:@"\n"]; for (int i=0; i < [stringLines count]; i++) { NSString *line = stringLines[i]; // Skip the last line if it is empty if (i != 0 && i == [stringLines count] - 1 && [line length] == 0) { continue; } NSString *prefixedWhitespace = [self getLeadingWhiteSpaceForString:line]; line = [line substringFromIndex:[prefixedWhitespace length]]; resultString = [[resultString stringByAppendingString:prefixedWhitespace] stringByAppendingString:[checkboxString stringByAppendingString:line]]; // Skip adding newline to the last line if (i != [stringLines count] - 1) { resultString = [resultString stringByAppendingString:@"\n"]; } addedCheckboxCount++; } didInsertCheckbox = YES; } NSTextStorage *storage = self.textStorage; [storage beginEditing]; [storage replaceCharactersInRange:lineRange withString:resultString]; [storage endEditing]; // Update the cursor position NSUInteger cursorAdjustment = 0; if (!cursorIsAtCheckbox) { if (selectionLength > 0 && didInsertCheckbox) { // Places cursor at end of insertion when text was selected cursorAdjustment = selectionLength + (ChecklistCursorAdjustment * addedCheckboxCount); } else { cursorAdjustment = didInsertCheckbox ? ChecklistCursorAdjustment : -ChecklistCursorAdjustment; } } [self setSelectedRange:NSMakeRange(cursorPosition + cursorAdjustment, 0)]; [self processChecklists]; [self.delegate textViewDidChange:self]; // Set the capitalization type to 'Words' temporarily so that we get a capital word next to the bullet. self.autocapitalizationType = UITextAutocapitalizationTypeWords; [self reloadInputViews]; } // Returns a NSString of any whitespace characters found at the start of a string - (NSString *)getLeadingWhiteSpaceForString: (NSString *)string { NSRegularExpression *regex = [[NSRegularExpression alloc] initWithPattern:@"^\\s*" options:0 error:NULL]; NSTextCheckingResult *match = [regex firstMatchInString:string options:0 range:NSMakeRange(0, string.length)]; return [string substringWithRange:match.range]; } - (void)onTextTapped:(UITapGestureRecognizer *)recognizer { NSUInteger characterIndex = [recognizer characterIndexInTextView:self]; if (characterIndex < self.textStorage.length) { if ([self handlePressedAttachmentAtIndex:characterIndex] || [self handlePressedLinkAtIndex:characterIndex]) { recognizer.cancelsTouchesInView = YES; return; } } CGPoint locationInView = [recognizer locationInView:self]; [self handlePressedLocation:locationInView]; recognizer.cancelsTouchesInView = NO; } - (void)handlePressedLocation:(CGPoint)point { [self becomeFirstResponder]; // Move the cursor to the tapped position UITextPosition *position = [self closestPositionToPoint:point]; UITextRange *range = [self textRangeFromPosition:position toPosition:position]; [self setSelectedTextRange:range]; } - (BOOL)handlePressedAttachmentAtIndex:(NSUInteger)characterIndex { NSRange attachmentRange; SPTextAttachment *attachment = [self.attributedText attribute:NSAttachmentAttributeName atIndex:characterIndex effectiveRange:&attachmentRange]; if ([attachment isKindOfClass:[SPTextAttachment class]] == false) { return NO; } BOOL wasChecked = attachment.isChecked; attachment.isChecked = !wasChecked; // iOS 13 Bugfix: // Move the TextView Selection to the end of the TextAttachment's line // This prevents the UIMenuController from showing up after toggling multiple TextAttachments in a row. [self selectEndOfLineForRange:attachmentRange]; // iOS 14 Bugfix: // Ensure the Attachment is onscreen. This prevents iOS 14 from bouncing back to the selected location if (@available(iOS 14.0, *)) { [self scrollRangeToVisible:self.selectedRange]; } [self.delegate textViewDidChange:self]; [self.layoutManager invalidateDisplayForCharacterRange:attachmentRange]; return YES; } - (BOOL)handlePressedLinkAtIndex:(NSUInteger)characterIndex { if (![self performsAggressiveLinkWorkaround]) { return NO; } NSURL *link = [self.attributedText attribute:NSLinkAttributeName atIndex:characterIndex effectiveRange:nil]; if ([link isKindOfClass:[NSURL class]] == NO || [link containsHttpScheme] == NO) { return NO; } [self.editorTextDelegate textView:self receivedInteractionWithURL:link]; return YES; } - (void)selectEndOfLineForRange:(NSRange)range { NSRange lineRange = [self.text lineRangeForRange:range]; if (lineRange.location == NSNotFound) { return; } NSInteger endOfLine = NSMaxRange(lineRange) - 1; if (endOfLine < 0 || endOfLine > self.textStorage.length) { return; } self.selectedRange = NSMakeRange(endOfLine, 0); } - (BOOL)performsAggressiveLinkWorkaround { if (@available(iOS 13.2, *)) { return NO; } if (@available(iOS 13, *)) { return YES; } return NO; } - (id<SPEditorTextViewDelegate>)editorTextDelegate { if ([self.delegate conformsToProtocol:@protocol(SPEditorTextViewDelegate)]) { return (id<SPEditorTextViewDelegate>)self.delegate; } return nil; } @end ```
/content/code_sandbox/Simplenote/Classes/SPEditorTextView.m
objective-c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
4,066
```swift import Foundation // MARK: - Simplenote's User Activities // enum ActivityType: String { /// Launch Simplenote Activity /// case launch = "com.codality.NotationalFlow.launch" /// New Note Activity /// case newNote = "com.codality.NotationalFlow.newNote" case newNoteShortcut = "OpenNewNoteIntent" /// Open a Note! /// case openNote = "com.codality.NotationalFlow.openNote" case openNoteShortcut = "OpenNoteIntent" /// Open an Item that was indexed by Spotlight /// case openSpotlightItem = "com.apple.corespotlightitem" } ```
/content/code_sandbox/Simplenote/Classes/ActivityType.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
144
```swift import UIKit // MARK: - UIScrollView // extension UIScrollView { /// Returns an offset that is checked against min and max offset /// func boundedContentOffset(from offset: CGPoint) -> CGPoint { let minXOffset = -adjustedContentInset.left let minYOffset = -adjustedContentInset.top let maxXOffset = contentSize.width - bounds.width + adjustedContentInset.right let maxYOffset = contentSize.height - bounds.height + adjustedContentInset.bottom return CGPoint(x: max(minXOffset, min(maxXOffset, offset.x)), y: max(minYOffset, min(maxYOffset, offset.y))) } } ```
/content/code_sandbox/Simplenote/Classes/UIScrollView+Simplenote.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
136
```objective-c // // UIImage+Colorization.m // // Created by Tom Witkin on 1/13/13. // #import "UIImage+Colorization.h" @implementation UIImage (Colorization) - (UIImage *)imageWithOverlayColor:(UIColor *)color { CGRect rect = CGRectMake(0.0f, 0.0f, self.size.width, self.size.height); CGFloat imageScale = self.scale; UIGraphicsBeginImageContextWithOptions(self.size, NO, imageScale); [self drawInRect:rect]; CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetBlendMode(context, kCGBlendModeSourceIn); CGContextSetFillColorWithColor(context, color.CGColor); CGContextFillRect(context, rect); UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return image; } @end ```
/content/code_sandbox/Simplenote/Classes/UIImage+Colorization.m
objective-c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
183
```objective-c // // SPTagTextView.m // Simplenote // // Created by Tom Witkin on 7/24/13. // #import "SPTagEntryField.h" #import "Simplenote-Swift.h" CGFloat const TagEntryFieldPadding = 40; @implementation SPTagEntryField - (instancetype)init { self = [super init]; if (self) { self.backgroundColor = [UIColor clearColor]; self.font = [UIFont preferredFontForTextStyle:UIFontTextStyleSubheadline]; self.textColor = [UIColor simplenoteTagViewTextColor]; self.placeholdTextColor = [UIColor simplenoteTagViewPlaceholderColor]; self.textAlignment = NSTextAlignmentNatural; self.placeholder = NSLocalizedString(@"Tag", @"Placeholder text in textfield when adding a new tag to a note"); self.returnKeyType = UIReturnKeyNext; self.autocorrectionType = UITextAutocorrectionTypeNo; self.autocapitalizationType = UITextAutocapitalizationTypeNone; self.accessibilityLabel = NSLocalizedString(@"Add tag", @"Label on button to add a new tag to a note"); self.accessibilityHint = NSLocalizedString(@"Add a tag to the current note", @"Accessibility hint for adding a tag to a note"); [self sizeField]; [self addTarget:self action:@selector(onTextChanged:) forControlEvents:UIControlEventEditingChanged]; } return self; } - (void)setText:(NSString *)text { [super setText:text]; // size field appropriately [self sizeField]; if ([self.tagDelegate respondsToSelector:@selector(tagEntryFieldDidChange:)]) { [self.tagDelegate tagEntryFieldDidChange:self]; } } - (void)sizeField { [self sizeToFit]; CGRect frame = self.frame; frame.size.width += 2 * TagEntryFieldPadding; frame.size.height = self.frame.size.height; self.frame = frame; } - (void)onTextChanged:(UITextField *)textField { dispatch_async(dispatch_get_main_queue(), ^{ if ([self.tagDelegate respondsToSelector:@selector(tagEntryFieldDidChange:)]) { [self.tagDelegate tagEntryFieldDidChange:self]; } [self sizeField]; }); } - (void)paste:(id)sender { [self pasteTag]; } @end ```
/content/code_sandbox/Simplenote/Classes/SPTagEntryField.m
objective-c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
484
```objective-c #import <UIKit/UIKit.h> #import "SPTransitionController.h" #import "SPSidebarContainerViewController.h" #import "Note.h" @class SPBlurEffectView; @class SPPlaceholderView; @class SPSortBar; @class NotesListController; @class SearchDisplayController; @interface SPNoteListViewController : UIViewController<SPSidebarContainerDelegate> @property (nonatomic, strong, readonly) SPBlurEffectView *navigationBarBackground; @property (nonatomic, strong, readonly) UISearchBar *searchBar; @property (nonatomic, assign, readonly) BOOL isIndexingNotes; @property (nonatomic, strong) UIImpactFeedbackGenerator *feedbackGenerator; @property (nonatomic, strong) SPPlaceholderView *placeholderView; @property (nonatomic, strong) NSLayoutConstraint *placeholderViewVerticalCenterConstraint; @property (nonatomic, strong) NSLayoutConstraint *placeholderViewTopConstraint; @property (nonatomic, strong) UITableView *tableView; @property (nonatomic, strong) UIStackView *searchBarStackView; @property (nonatomic, strong, readonly) SearchDisplayController *searchController; @property (nonatomic, strong) NotesListController *notesListController; @property (nonatomic) CGFloat noteRowHeight; @property (nonatomic) CGFloat tagRowHeight; @property (nonatomic) CGFloat keyboardHeight; @property (nonatomic) BOOL firstLaunch; @property (nonatomic) BOOL mustScrollToFirstRow; @property (nonatomic, strong) UIBarButtonItem *emptyTrashButton; @property (nonatomic, strong) UIBarButtonItem *trashButton; @property (nonatomic, strong) UIBarButtonItem *addButton; @property (nonatomic, strong) UIBarButtonItem *selectAllButton; @property (nonatomic, weak) Note *selectedNote; @property (nonatomic) BOOL navigatingUsingKeyboard; @property (nonatomic) NSArray<NSIndexPath *> *selectedNotesEnteringBackground; - (void)update; - (void)openNote:(Note *)note animated:(BOOL)animated; - (void)openNote:(Note *)note ignoringSearchQuery:(BOOL)ignoringSearchQuery animated:(BOOL)animated; - (void)setWaitingForIndex:(BOOL)waiting; - (void)startSearching; - (void)endSearching; - (void)updateNavigationBar; @end ```
/content/code_sandbox/Simplenote/Classes/SPNoteListViewController.h
objective-c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
447
```swift import UIKit class SPSimpleTextPrintFormatter: UISimpleTextPrintFormatter { override init(text: String) { super.init(text: text) // Check for darkmode // If dark mode is enabled change the text color to black before printing if SPUserInterface.isDark { self.color = .black } } } ```
/content/code_sandbox/Simplenote/Classes/SPSimpleTextPrintFormatter.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
76
```swift import Foundation // MARK: - UINavigationController Simplenote API // extension UINavigationController { /// Returns the first Child ViewController of the specified Type /// func firstChild<T: UIViewController>(ofType type: T.Type) -> T? { for child in children where child is T { return child as? T } return nil } } ```
/content/code_sandbox/Simplenote/Classes/UINavigationController+Simplenote.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
77
```swift import Foundation // MARK: - UINavigationBar + Appearance // extension UINavigationBar { /// Applies the Simplenote Appearance to `UINavigationBar` instances /// class func refreshAppearance() { let clearImage = UIImage() let apperance = UINavigationBar.appearance(whenContainedInInstancesOf: [SPNavigationController.self]) apperance.barTintColor = .clear apperance.shadowImage = clearImage apperance.titleTextAttributes = [ .font: UIFont.systemFont(ofSize: 17, weight: .semibold), .foregroundColor: UIColor.simplenoteNavigationBarTitleColor ] apperance.setBackgroundImage(clearImage, for: .default) apperance.setBackgroundImage(clearImage, for: .defaultPrompt) } } ```
/content/code_sandbox/Simplenote/Classes/UINavigationBar+Appearance.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
172
```objective-c #import "SPNoteListViewController.h" #import "SPSettingsViewController.h" #import "SPNavigationController.h" #import "SPNoteEditorViewController.h" #import "SPAppDelegate.h" #import "SPTransitionController.h" #import "SPTextView.h" #import "SPObjectManager.h" #import "SPTracker.h" #import "SPRatingsHelper.h" #import "SPConstants.h" #import "Note.h" #import "NSMutableAttributedString+Styling.h" #import <StoreKit/StoreKit.h> #import <Simperium/Simperium.h> #import "Simplenote-Swift.h" @interface SPNoteListViewController () <UITextFieldDelegate, SearchDisplayControllerDelegate, SearchControllerPresentationContextProvider, SPRatingsPromptDelegate> @property (nonatomic, strong) NSTimer *searchTimer; @property (nonatomic, strong) SPBlurEffectView *navigationBarBackground; @property (nonatomic, strong) UIBarButtonItem *sidebarButton; @property (nonatomic, strong) SearchDisplayController *searchController; @property (nonatomic, strong) UIActivityIndicatorView *activityIndicator; @property (nonatomic, strong) SPTransitionController *transitionController; @property (nonatomic, assign) BOOL bTitleViewAnimating; @property (nonatomic, assign) BOOL bResetTitleView; @property (nonatomic, assign) BOOL isIndexingNotes; @end @implementation SPNoteListViewController - (instancetype)init { self = [super init]; if (self) { [self configureImpactGenerator]; [self configureNavigationButtons]; [self configureNavigationBarBackground]; [self configureResultsController]; [self configurePlaceholderView]; [self configureTableView]; [self configureSearchController]; [self configureSearchStackView]; [self configureRootView]; [self updateTableViewMetrics]; [self startListeningToNotifications]; [self startDisplayingEntities]; [self refreshStyle]; [self update]; self.mustScrollToFirstRow = YES; self.selectedNotesEnteringBackground = [NSArray new]; } return self; } #pragma mark - View Lifecycle - (void)viewDidLayoutSubviews { [super viewDidLayoutSubviews]; [self refreshTableViewTopInsets]; [self updateTableHeaderSize]; [self ensureFirstRowIsVisibleIfNeeded]; } - (void)willMoveToParentViewController:(UIViewController *)parent { [super willMoveToParentViewController:parent]; [self ensureFirstRowIsVisible]; [self ensureTransitionControllerIsInitialized]; } - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; [self refershNavigationButtons]; if (!self.navigatingUsingKeyboard) { [self.tableView deselectSelectedRowAnimated:YES]; self.selectedNote = nil; } self.navigatingUsingKeyboard = NO; [self refreshStyle]; } - (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; [self showRatingViewIfNeeded]; } - (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; if (![SPAppDelegate sharedDelegate].simperium.user) { [self setWaitingForIndex:YES]; } } - (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection { [super traitCollectionDidChange:previousTraitCollection]; if ([previousTraitCollection hasDifferentColorAppearanceComparedToTraitCollection:self.traitCollection] == false) { return; } [self themeDidChange]; } - (void)ensureTransitionControllerIsInitialized { if (_transitionController != nil) { return; } NSAssert(self.navigationController != nil, @"we should be already living within a navigationController before this method can be called"); self.transitionController = [[SPTransitionController alloc] initWithNavigationController:self.navigationController]; self.navigationController.delegate = self.transitionController; } - (void)updateTableViewMetrics { self.noteRowHeight = SPNoteTableViewCell.cellHeight; self.tagRowHeight = SPTagTableViewCell.cellHeight; [self reloadTableData]; } - (void)updateTableHeaderSize { UIView *headerView = self.tableView.tableHeaderView; if (!headerView) { return; } // Old school workaround. tableHeaderView isn't really Autolayout friendly. [headerView adjustSizeForCompressedLayout]; self.tableView.tableHeaderView = headerView; } #pragma mark - Overridden Properties - (UIStatusBarStyle)preferredStatusBarStyle { return self.navigationController.preferredStatusBarStyle; } #pragma mark - Dynamic Properties - (UISearchBar *)searchBar { return _searchController.searchBar; } - (UIActivityIndicatorView *)activityIndicator { if (_activityIndicator == nil) { _activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleMedium]; } return _activityIndicator; } #pragma mark - Notifications - (void)startListeningToNotifications { NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; // Dynamic Fonts! [nc addObserver:self selector:@selector(contentSizeWasUpdated:) name:UIContentSizeCategoryDidChangeNotification object:nil]; // Condensed Notes [nc addObserver:self selector:@selector(condensedPreferenceWasUpdated:) name:SPCondensedNoteListPreferenceChangedNotification object:nil]; [nc addObserver:self selector:@selector(sortModePreferenceWasUpdated:) name:SPNotesListSortModeChangedNotification object:nil]; // Register for keyboard notifications [nc addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil]; // Themes [nc addObserver:self selector:@selector(themeDidChange) name:SPSimplenoteThemeChangedNotification object:nil]; // App Background [nc addObserver:self selector:@selector(appWillEnterBackground) name:UIApplicationDidEnterBackgroundNotification object:nil]; [nc addObserver:self selector:@selector(appWillEnterForeground) name:UIApplicationWillEnterForegroundNotification object:nil]; } - (void)condensedPreferenceWasUpdated:(id)sender { [self updateTableViewMetrics]; } - (void)contentSizeWasUpdated:(id)sender { [self updateTableViewMetrics]; } - (void)sortModePreferenceWasUpdated:(id)sender { [self update]; } - (void)themeDidChange { [self refreshStyle]; } - (void)appWillEnterBackground { self.selectedNotesEnteringBackground = self.tableView.indexPathsForSelectedRows; } - (void)appWillEnterForeground { [self restoreSelectedRowsAfterBackgrounding]; } - (void)refreshStyle { // Refresh the containerView's backgroundColor self.view.backgroundColor = [UIColor simplenoteBackgroundColor]; // Refresh the Table's UI [self.tableView applySimplenotePlainStyle]; [self reloadTableData]; // Refresh the SearchBar's UI [self.searchBar applySimplenoteStyle]; self.navigationController.toolbar.translucent = false; self.navigationController.toolbar.barTintColor = [UIColor simplenoteSortBarBackgroundColor]; } - (void)refershNavigationButtons { [self refreshNavigationBarLabels]; [self updateNavigationBar]; [self refreshNavigationControllerToolbar]; } - (void)refreshNavigationControllerToolbar { [self.navigationController setToolbarHidden:!self.isEditing animated:YES]; [self configureNavigationToolbarButton]; } - (void)updateNavigationBar { // TODO: When multi select is added to iPad, revist the conditionals here [self.navigationController setNavigationBarHidden: self.isSearchActive animated:YES]; UIBarButtonItem *addOrEditButton = self.isEditing ? self.editButtonItem : self.addButton; UIBarButtonItem *rightButton = (self.isDeletedFilterActive) ? self.emptyTrashButton : addOrEditButton; UIBarButtonItem *leftButton = self.isEditing ? self.selectAllButton : self.sidebarButton; [self.navigationItem setRightBarButtonItem:rightButton animated:YES]; [self.navigationItem setLeftBarButtonItem:leftButton animated:YES]; } #pragma mark - Interface Initialization - (void)configureNavigationButtons { NSAssert(_addButton == nil, @"_addButton is already initialized!"); NSAssert(_sidebarButton == nil, @"_sidebarButton is already initialized!"); NSAssert(_emptyTrashButton == nil, @"_emptyTrashButton is already initialized!"); NSAssert(_selectAllButton == nil, @"_selectAllButton is already initialized!"); /// Button: New Note /// self.addButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageWithName:UIImageNameNewNote] style:UIBarButtonItemStylePlain target:self action:@selector(addButtonAction:)]; self.addButton.isAccessibilityElement = YES; self.addButton.accessibilityLabel = NSLocalizedString(@"New note", nil); self.addButton.accessibilityHint = NSLocalizedString(@"Create a new note", nil); /// Button: Display Tags /// self.sidebarButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageWithName:UIImageNameMenu] style:UIBarButtonItemStylePlain target:self action:@selector(sidebarButtonAction:)]; self.sidebarButton.isAccessibilityElement = YES; self.sidebarButton.accessibilityIdentifier = @"menu"; self.sidebarButton.accessibilityLabel = NSLocalizedString(@"Sidebar", @"UI region to the left of the note list which shows all of a users tags"); self.sidebarButton.accessibilityHint = NSLocalizedString(@"Toggle tag sidebar", @"Accessibility hint used to show or hide the sidebar"); /// Button: Empty Trash /// self.emptyTrashButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"Empty", @"Verb - empty causes all notes to be removed permenently from the trash") style:UIBarButtonItemStylePlain target:self action:@selector(emptyAction:)]; self.emptyTrashButton.isAccessibilityElement = YES; self.emptyTrashButton.accessibilityLabel = NSLocalizedString(@"Empty trash", @"Remove all notes from the trash"); self.emptyTrashButton.accessibilityHint = NSLocalizedString(@"Remove all notes from trash", nil); self.trashButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageWithName:UIImageNameTrash] style:UIBarButtonItemStylePlain target:self action:@selector(trashSelectedNotes)]; self.trashButton.isAccessibilityElement = YES; self.trashButton.accessibilityLabel = NSLocalizedString(@"Trash Notes", @"Move selected notes to trash"); self.trashButton.accessibilityHint = NSLocalizedString(@"Move selected notes to trash", @"Accessibility hint for trash selected notes button"); NSString *selectAllTitle = NSLocalizedString(@"Select All", @"Select all button title"); self.selectAllButton = [[UIBarButtonItem alloc] initWithTitle: selectAllTitle style:UIBarButtonItemStylePlain target:self action:@selector(selectAllWasTapped)]; [self refreshEditButtonTitle]; } - (void)configureNavigationBarBackground { NSAssert(_navigationBarBackground == nil, @"_navigationBarBackground is already initialized!"); // What's going on: // - SPNavigationController.displaysBlurEffect makes sense when every VC in the hierarchy displays blur. // - Since our UISearchBar lives in our View Hierarchy, the blur cannot be dealt with by the NavigationBar. // - Therefore we must inject the blur on a VC per VC basis. // self.navigationBarBackground = [SPBlurEffectView navigationBarBlurView]; } - (void)configureSearchController { NSAssert(_searchController == nil, @"_searchController is already initialized!"); self.searchController = [SearchDisplayController new]; self.searchController.delegate = self; self.searchController.presenter = self; self.searchBar.placeholder = NSLocalizedString(@"Search notes or tags", @"SearchBar's Placeholder Text"); [self.searchBar applySimplenoteStyle]; [self.searchBar refreshPlaceholderStyleWithSearchEnabled:YES]; self.searchController.searchBar.accessibilityIdentifier = @"search-bar"; } #pragma mark - BarButtonActions - (void)addButtonAction:(id)sender { [self createNewNote]; } - (void)sidebarButtonAction:(id)sender { [self setEditing:NO]; [SPTracker trackSidebarButtonPresed]; [[[SPAppDelegate sharedDelegate] sidebarViewController] toggleSidebar]; } #pragma mark - SPSearchControllerDelegate methods - (BOOL)searchDisplayControllerShouldBeginSearch:(SearchDisplayController *)controller { return YES; } - (void)searchDisplayController:(SearchDisplayController *)controller updateSearchResults:(NSString *)keyword { // Don't search immediately; search a tad later to improve performance of search-as-you-type [self invalidateSearchTimer]; NSTimeInterval const delay = 0.2; self.searchTimer = [NSTimer scheduledTimerWithTimeInterval:delay repeats:NO block:^(NSTimer * _Nonnull timer) { [self performSearchWithKeyword:keyword]; }]; } - (void)searchDisplayControllerWillBeginSearch:(SearchDisplayController *)controller { self.selectedNote = nil; [self.tableView deselectSelectedRowAnimated:NO]; // Note: We avoid switching to SearchMode in `shouldBegin` because it might cause layout issues! [self.notesListController beginSearch]; [self reloadTableData]; [self refreshTitle]; [self refershNavigationButtons]; [self.editButtonItem setEnabled:NO]; [self setEditing:NO animated:YES]; } - (void)searchDisplayControllerDidEndSearch:(SearchDisplayController *)controller { [self invalidateSearchTimer]; /// Note: /// - `endSearch` switches the List Controller to `.results`, and drops immediately the Tags section (if any) /// - `dismissSortBar` may (under unknown scenarios) trigger a UITableView refresh sequence /// /// Because of the reasons above, we must always ensure `endSearch` is followed by `update` (which reloads the table!) /// /// Ref. path_to_url /// [self.notesListController endSearch]; [self refershNavigationButtons]; [self update]; [self.editButtonItem setEnabled:YES]; } #pragma mark - SPSearchControllerPresenter methods - (UINavigationController *)navigationControllerForSearchDisplayController:(SearchDisplayController *)controller { return self.navigationController; } #pragma mark - Search Helpers - (void)performSearchWithKeyword:(NSString *)keyword { [SPTracker trackListNotesSearched]; self.selectedNote = nil; [self.tableView deselectSelectedRowAnimated:NO]; [self.notesListController refreshSearchResultsWithKeyword:keyword]; [self.tableView scrollToTopWithAnimation:NO]; [self reloadTableData]; [self displayPlaceholdersIfNeeded]; [self invalidateSearchTimer]; } - (void)startSearching { [self.searchController.searchBar becomeFirstResponder]; } - (void)endSearching { [self.searchController dismiss]; } - (void)invalidateSearchTimer { [self.searchTimer invalidate]; self.searchTimer = nil; } #pragma mark - UIScrollView Delegate - (void)scrollViewDidScroll:(UIScrollView *)scrollView { // Slowly Fade-In the NavigationBar's Blur [self.navigationBarBackground adjustAlphaMatchingContentOffsetOf:scrollView]; } #pragma mark - Public API - (void)openNote:(Note *)note animated:(BOOL)animated { [self openNote:note ignoringSearchQuery:NO animated:animated]; } - (void)openNote:(Note *)note ignoringSearchQuery:(BOOL)ignoringSearchQuery animated:(BOOL)animated { [SPTracker trackListNoteOpened]; self.selectedNote = note; [self updateCurrentSelection]; // SearchBar: Always resign FirstResponder status // Why: path_to_url [self.searchBar resignFirstResponder]; // Always a new Editor! SPNoteEditorViewController *editor = [[EditorFactory shared] buildWith:note]; if (!ignoringSearchQuery && self.isSearchActive) { [editor updateWithSearchQuery:self.searchQuery]; } [self.navigationController setViewControllers:@[self, editor] animated:animated]; } - (void)emptyAction:(id)sender { NSString *message = NSLocalizedString(@"Are you sure you want to empty the trash? This cannot be undone.", @"Empty Trash Warning"); UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:message preferredStyle:UIAlertControllerStyleAlert]; NSString *cancelText = NSLocalizedString(@"No", @"Cancels Empty Trash Action"); UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:cancelText style:UIAlertActionStyleCancel handler:nil]; NSString *acceptText = NSLocalizedString(@"Yes", @"Proceeds with the Empty Trash OP"); UIAlertAction *acceptAction = [UIAlertAction actionWithTitle:acceptText style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) { [self emptyTrash]; }]; [alertController addAction:cancelAction]; [alertController addAction:acceptAction]; [self presentViewController:alertController animated:true completion:nil]; } - (void)emptyTrash { [SPTracker trackListTrashEmptied]; [[SPObjectManager sharedManager] emptyTrash]; [self.emptyTrashButton setEnabled:NO]; [self displayPlaceholdersIfNeeded]; } #pragma mark - NoteListController - (void)update { [self refreshListController]; [self refreshTitle]; [self refreshSearchBar]; [self refreshEmptyTrashState]; [self displayPlaceholdersIfNeeded]; [self refershNavigationButtons]; [self hideRatingViewIfNeeded]; } #pragma mark - SPSidebarContainerDelegate - (BOOL)sidebarContainerShouldDisplaySidebar:(SPSidebarContainerViewController *)sidebarContainer { // Checking for self.tableView.isEditing prevents showing the sidebar when you use swipe to cancel delete/restore. return !(self.tableView.dragging || self.tableView.isEditing || self.isSearchActive); } - (void)sidebarContainerWillDisplaySidebar:(SPSidebarContainerViewController *)sidebarContainer { self.tableView.scrollEnabled = NO; self.tableView.userInteractionEnabled = NO; self.searchBar.userInteractionEnabled = NO; self.navigationController.navigationBar.userInteractionEnabled = NO; } - (void)sidebarContainerDidDisplaySidebar:(SPSidebarContainerViewController *)sidebarContainer { // NO-OP } - (void)sidebarContainerWillHideSidebar:(SPSidebarContainerViewController *)sidebarContainer { // NO-OP: The navigationBar's top right button is refreshed via the regular `Update` sequence. } - (void)sidebarContainerDidHideSidebar:(SPSidebarContainerViewController *)sidebarContainer { self.tableView.scrollEnabled = YES; self.tableView.userInteractionEnabled = YES; self.searchBar.userInteractionEnabled = YES; self.navigationController.navigationBar.userInteractionEnabled = YES; // We want this VC to be first responder to support keyboard shortcuts. // We don't want to steal first responder from the search bar in case it's already active. // It Can happen if we open the app directly into search mode from the home screen quick action if (![self.searchBar isFirstResponder]) { [self becomeFirstResponder]; } } #pragma mark - Index progress - (void)setWaitingForIndex:(BOOL)waiting { // if the current tag is the deleted tag, do not show the activity spinner if (self.isDeletedFilterActive && waiting) { return; } if (waiting && self.navigationItem.titleView == nil && (self.isListEmpty || _firstLaunch)){ [self.activityIndicator startAnimating]; self.bResetTitleView = NO; [self animateTitleViewSwapWithNewView:self.activityIndicator completion:nil]; } else if (!waiting && self.navigationItem.titleView != nil && !self.bTitleViewAnimating) { [self resetTitleView]; } else if (!waiting) { self.bResetTitleView = YES; } self.isIndexingNotes = waiting; [self displayPlaceholdersIfNeeded]; } - (void)animateTitleViewSwapWithNewView:(UIView *)newView completion:(void (^)())completion { self.bTitleViewAnimating = YES; [UIView animateWithDuration:UIKitConstants.animationShortDuration animations:^{ self.navigationItem.titleView.alpha = UIKitConstants.alpha0_0; } completion:^(BOOL finished) { self.navigationItem.titleView = newView; [UIView animateWithDuration:UIKitConstants.animationShortDuration animations:^{ self.navigationItem.titleView.alpha = UIKitConstants.alpha1_0; } completion:^(BOOL finished) { if (completion) { completion(); } self.bTitleViewAnimating = NO; if (self.bResetTitleView) { [self resetTitleView]; } }]; }]; } - (void)resetTitleView { [self animateTitleViewSwapWithNewView:nil completion:^{ self.bResetTitleView = NO; [self.activityIndicator stopAnimating]; }]; } #pragma mark - Ratings View Helpers - (void)showRatingViewIfNeeded { if (![[SPRatingsHelper sharedInstance] shouldPromptForAppReview]) { return; } [SPTracker trackRatingsPromptSeen]; UIView *ratingsView = self.tableView.tableHeaderView ?: [self newRatingsView]; // Calculate the minimum required dimension [ratingsView adjustSizeForCompressedLayout]; // UITableView will adjust the HeaderView's width. Right afterwards, we'll perform a layout cycle, to avoid glitches self.tableView.tableHeaderView = ratingsView; [ratingsView layoutIfNeeded]; // And finally ... FadeIn! ratingsView.alpha = UIKitConstants.alpha0_0; [UIView animateWithDuration:UIKitConstants.animationShortDuration delay:UIKitConstants.animationDelayZero options:UIViewAnimationOptionCurveEaseIn animations:^{ ratingsView.alpha = UIKitConstants.alpha1_0; [self.tableView layoutIfNeeded]; } completion:nil]; } - (void)hideRatingViewIfNeeded { if (self.tableView.tableHeaderView == nil || [[SPRatingsHelper sharedInstance] shouldPromptForAppReview] == YES) { return; } [UIView animateWithDuration:UIKitConstants.animationShortDuration delay:UIKitConstants.animationDelayZero options:UIViewAnimationOptionCurveEaseIn animations:^{ self.tableView.tableHeaderView = nil; [self.tableView layoutIfNeeded]; } completion:nil]; } - (UIView *)newRatingsView { SPRatingsPromptView *ratingsView = [SPRatingsPromptView loadFromNib]; ratingsView.delegate = self; return ratingsView; } #pragma mark - SPRatingsPromptDelegate - (void)displayReviewUI { [SKStoreReviewController requestReviewInScene:UIApplication.sharedApplication.foregroundWindowScene]; [SPTracker trackRatingsAppRated]; [[SPRatingsHelper sharedInstance] ratedCurrentVersion]; [self hideRatingViewIfNeeded]; } - (void)displayFeedbackUI { UIViewController *feedbackViewController = [[SPFeedbackManager shared] feedbackViewController]; feedbackViewController.modalPresentationStyle = UIModalPresentationFormSheet; [self presentViewController:feedbackViewController animated:YES completion:nil]; [SPTracker trackRatingsFeedbackScreenOpened]; [[SPRatingsHelper sharedInstance] gaveFeedbackForCurrentVersion]; [self hideRatingViewIfNeeded]; } - (void)dismissRatingsUI { [SPTracker trackRatingsDeclinedToRate]; [[SPRatingsHelper sharedInstance] declinedToRateCurrentVersion]; [self hideRatingViewIfNeeded]; } - (void)simplenoteWasLiked { [SPTracker trackRatingsAppLiked]; [[SPRatingsHelper sharedInstance] likedCurrentVersion]; } - (void)simplenoteWasDisliked { [SPTracker trackRatingsAppDisliked]; [[SPRatingsHelper sharedInstance] dislikedCurrentVersion]; } @end ```
/content/code_sandbox/Simplenote/Classes/SPNoteListViewController.m
objective-c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
4,903
```swift import UIKit // MARK: - TagListTextField // class TagListTextField: UITextField { override func paste(_ sender: Any?) { pasteTag() } } ```
/content/code_sandbox/Simplenote/Classes/TagListTextField.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
37
```objective-c // // SPNotifications.m // Simplenote // // #import "SPNotifications.h" #pragma mark ================================================================================ #pragma mark Notifications #pragma mark ================================================================================ NSString *const SPAlphabeticalTagSortPreferenceChangedNotification = @"SPAlphabeticalTagSortPreferenceChangedNotification"; NSString *const SPCondensedNoteListPreferenceChangedNotification = @"SPCondensedNoteListPreferenceChangedNotification"; NSString *const SPNotesListSortModeChangedNotification = @"SPNotesListSortModeChangedNotification"; NSString *const SPSimplenoteThemeChangedNotification = @"SPSimplenoteThemeChangedNotification"; NSString *const SPSubscriptionStatusDidChangeNotification = @"SPSubscriptionStatusDidChangeNotification"; ```
/content/code_sandbox/Simplenote/Classes/SPNotifications.m
objective-c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
144
```objective-c // // SPEditorTextView.h // Simplenote // // Created by Tom Witkin on 8/16/13. // #import "SPTextView.h" @protocol SPEditorTextViewDelegate <UITextViewDelegate> - (void)textView:(UITextView *)textView receivedInteractionWithURL:(NSURL *)url; @end @interface SPEditorTextView : SPTextView @property (nonatomic, strong) UIFont *checklistsFont; @property (nonatomic, strong) UIColor *checklistsTintColor; @property (nonatomic, readonly) BOOL isInserting; @property (nonatomic, readonly) BOOL isDeletingBackward; @property (nonatomic, strong) void (^onContentPositionChange)(void); - (void)scrollToBottomWithAnimation:(BOOL)animated; - (void)scrollToTop; - (void)processChecklists; - (void)insertOrRemoveChecklist; /// iOS 13.0 + 13.1 had an usability issue that rendered link interactions within a UITextView next to impossible. /// Since such issue has bene fixed in 13.2, we're containing the custom behavior to the broken release. /// /// Whenever this method returns *true*, link interactions will be passed along via the `textView:receivedInteractionWithURL:` delegate method. /// /// Ref.: path_to_url /// - (BOOL)performsAggressiveLinkWorkaround; @end ```
/content/code_sandbox/Simplenote/Classes/SPEditorTextView.h
objective-c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
277
```objective-c #import "NSString+Metadata.h" @implementation NSString (Metadata) - (NSArray *)stringArray { NSMutableArray *list = [NSMutableArray arrayWithArray: [self componentsSeparatedByString:@" "]]; NSMutableArray *discardedItems = [NSMutableArray array]; NSString *str; for (str in list) { if ([str length] == 0) [discardedItems addObject:str]; } [list removeObjectsInArray:discardedItems]; return list; } @end ```
/content/code_sandbox/Simplenote/Classes/NSString+Metadata.m
objective-c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
101
```swift import Foundation import SimplenoteFoundation // MARK: - InterlinkResultsController // class InterlinkResultsController { /// ResultsController: In charge of CoreData Queries! /// private let resultsController: ResultsController<Note> /// Limits the maximum number of results to fetch /// var maximumNumberOfResults = Settings.defaultMaximumResults /// Designated Initializer /// init(viewContext: NSManagedObjectContext) { resultsController = ResultsController<Note>(viewContext: viewContext, sortedBy: [ NSSortDescriptor(keyPath: \Note.content, ascending: true) ]) resultsController.predicate = NSPredicate.predicateForNotes(deleted: false) try? resultsController.performFetch() } /// Returns the collection of Notes filtered by the specified Keyword in their title, excluding a specific ObjectID /// - Important: Returns `nil` when there are no results! /// func searchNotes(byTitleKeyword keyword: String, excluding excludedID: NSManagedObjectID?) -> [Note]? { filter(notes: resultsController.fetchedObjects, byTitleKeyword: keyword, excluding: excludedID) } } // MARK: - Private // private extension InterlinkResultsController { /// Filters a collection of notes by their Title contents, excluding a specific Object ID. /// /// - Important: Why do we perform an *in memory* filtering? /// - CoreData's SQLite store does not support block based predicates /// - RegExes aren't diacritic + case insensitve friendly /// - It's easier and anyone can follow along! /// func filter(notes: [Note], byTitleKeyword keyword: String, excluding excludedID: NSManagedObjectID?) -> [Note]? { let comparisonOptions: NSString.CompareOptions = [.diacriticInsensitive, .caseInsensitive] let normalizedKeyword = keyword.trimmingCharacters(in: .whitespacesAndNewlines) var output = [Note]() for note in notes where note.objectID != excludedID { note.ensurePreviewStringsAreAvailable() guard let title = note.titlePreview, let _ = title.range(of: normalizedKeyword, options: comparisonOptions, range: title.fullRange, locale: .current) else { continue } output.append(note) if output.count >= maximumNumberOfResults { break } } return output.isEmpty ? nil : output } } // MARK: - Settings! // private enum Settings { static let defaultMaximumResults = 15 } ```
/content/code_sandbox/Simplenote/Classes/InterlinkResultsController.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
533
```swift import Foundation import UIKit import SafariServices import SwiftUI // MARK: - SPOnboardingViewController // class SPOnboardingViewController: UIViewController, SPAuthenticationInterface { /// Message: Container View /// @IBOutlet var messageView: UIView! /// Message: Text Label /// @IBOutlet var messageLabel: UILabel! /// Top Image /// @IBOutlet var simplenoteImageView: UIImageView! /// Top Label /// @IBOutlet var simplenoteLabel: UILabel! /// Header /// @IBOutlet var headerLabel: UILabel! /// SignUp Button /// @IBOutlet var signUpButton: SPSquaredButton! /// Login Button /// @IBOutlet var loginButton: UIButton! /// Indicates if Extended Debugging has been enabled /// private var debugEnabled = false /// Simperium's Authenticator Instance /// var authenticator: SPAuthenticator? // MARK: - Overriden Properties override var supportedInterfaceOrientations: UIInterfaceOrientationMask { return .portrait } override var shouldAutorotate: Bool { return false } // MARK: - Overridden Methods override func viewDidLoad() { super.viewDidLoad() setupNavigationItem() setupNavigationController() setupMessageView() setupImageView() setupLabels() setupActionButtons() startListeningToNotifications() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) ensureNavigationBarIsHidden() } } // MARK: - Private // private extension SPOnboardingViewController { func setupNavigationItem() { navigationItem.backBarButtonItem = UIBarButtonItem(title: String(), style: .plain, target: nil, action: nil) } func setupNavigationController() { navigationController?.navigationBar.applyLightStyle() navigationController?.overrideUserInterfaceStyle = .light } func setupMessageView() { messageView.backgroundColor = .simplenoteRed50Color messageView.layer.cornerRadius = signUpButton.cornerRadius } func setupActionButtons() { signUpButton.setTitle(OnboardingStrings.signupText, for: .normal) signUpButton.setTitleColor(.white, for: .normal) signUpButton.backgroundColor = .simplenoteBlue50Color loginButton.setTitle(OnboardingStrings.loginText, for: .normal) loginButton.setTitleColor(.simplenoteBlue50Color, for: .normal) } func setupImageView() { simplenoteImageView.tintColor = .simplenoteBlue50Color } func setupLabels() { simplenoteLabel.text = OnboardingStrings.brandText simplenoteLabel.textColor = UIColor.simplenoteGray100Color simplenoteLabel.adjustsFontSizeToFitWidth = true simplenoteLabel.font = .preferredFont(for: .largeTitle, weight: .semibold) headerLabel.text = OnboardingStrings.headerText headerLabel.textColor = UIColor.simplenoteGray50Color headerLabel.adjustsFontSizeToFitWidth = true headerLabel.font = .preferredFont(forTextStyle: .title3) } func displayDebugMessage(enabled: Bool) { let text = enabled ? OnboardingStrings.debugEnabled : OnboardingStrings.debugDisabled let backgroundColor = enabled ? UIColor.simplenoteRed50Color : .simplenoteGray50Color display(message: text, backgroundColor: backgroundColor) } func display(message: String, backgroundColor: UIColor) { messageLabel.text = message messageView.isHidden = false messageView.alpha = UIKitConstants.alpha0_0 messageView.backgroundColor = backgroundColor UIView.animate(withDuration: UIKitConstants.animationShortDuration) { self.messageView.alpha = UIKitConstants.alpha1_0 } UIView.animate(withDuration: UIKitConstants.animationLongDuration, delay: UIKitConstants.animationDelayLong, options: [], animations: { self.messageView.alpha = UIKitConstants.alpha0_0 }, completion: nil) } } // MARK: - Actions // private extension SPOnboardingViewController { @IBAction func signupWasPressed() { presentAuthenticationInterface(mode: .signup) } @IBAction func loginWasPressed() { presentAuthenticationInterface(mode: .requestLoginCode) } @IBAction func unlockDebugMode() { debugEnabled.toggle() displayDebugMessage(enabled: debugEnabled) } func ensureNavigationBarIsHidden() { navigationController?.setNavigationBarHidden(true, animated: true) } func presentAuthenticationInterface(mode: AuthenticationMode) { guard let simperiumAuthenticator = authenticator else { fatalError("Missing Simperium Authenticator Instance") } let controller = SPAuthHandler(simperiumService: simperiumAuthenticator) let viewController = SPAuthViewController(controller: controller, mode: mode) viewController.debugEnabled = debugEnabled navigationController?.pushViewController(viewController, animated: true) } } // MARK: - Actions // private extension SPOnboardingViewController { func startListeningToNotifications() { let name = NSNotification.Name(rawValue: kSignInErrorNotificationName) let nc = NotificationCenter.default nc.addObserver(self, selector: #selector(handleSignInError), name: name, object: nil) nc.addObserver(self, selector: #selector(handleMagicLinkAuthDidFail), name: .magicLinkAuthDidFail, object: nil) } @objc func handleSignInError(note: Notification) { let message = note.userInfo?[NSLocalizedDescriptionKey] as? String ?? SignInError.genericErrorText let alertController = UIAlertController(title: SignInError.title, message: message, preferredStyle: .alert) alertController.addDefaultActionWithTitle(SignInError.acceptButtonText) /// SFSafariViewController _might_ be onscreen presentedViewController?.dismiss(animated: true, completion: nil) present(alertController, animated: true, completion: nil) } @objc func handleMagicLinkAuthDidFail() { DispatchQueue.main.async { self.presentMagicLinkInvalidView() } } } // MARK: - Magic Link Helpers // private extension SPOnboardingViewController { /// Presents the Invalid Magic Link UI /// private func presentMagicLinkInvalidView() { var rootView = MagicLinkInvalidView() rootView.onPressRequestNewLink = { [weak self] in self?.presentAuthenticationInterfaceIfNeeded(mode: .requestLoginCode) } let hostingController = UIHostingController(rootView: rootView) hostingController.modalPresentationStyle = .formSheet hostingController.sheetPresentationController?.detents = [.medium()] let presenter = navigationController?.visibleViewController ?? self presenter.present(hostingController, animated: true) } /// Dismisses all of the presented ViewControllers, and pushes the Authentication UI with the specified mode. /// - Note: Whenever the required AuthUI is already onscreen, we'll do nothing /// func presentAuthenticationInterfaceIfNeeded(mode: AuthenticationMode) { navigationController?.popToRootViewController(animated: true) presentAuthenticationInterface(mode: mode) } } // MARK: - Private Types // private struct OnboardingStrings { static let debugDisabled = NSLocalizedString("Debug Disabled", comment: "Indicates that Extended Debugging has been disabled") static let debugEnabled = NSLocalizedString(" Debug Enabled ", comment: "Indicates that Extended Debugging has been enabled") static let brandText = NSLocalizedString("Simplenote", comment: "Our mighty brand!") static let signupText = NSLocalizedString("Sign Up", comment: "Signup Action") static let loginText = NSLocalizedString("Log In", comment: "Login Action") static let headerText = NSLocalizedString("The simplest way to keep notes.", comment: "Onboarding Header Text") } private struct SignInError { static let title = NSLocalizedString("Couldn't Sign In", comment: "Alert dialog title displayed on sign in error") static let genericErrorText = NSLocalizedString("An error was encountered while signing in.", comment: "Sign in error message") static let acceptButtonText = NSLocalizedString("OK", comment: "Dismisses an AlertController") } ```
/content/code_sandbox/Simplenote/Classes/SPOnboardingViewController.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
1,718
```swift import Foundation // MARK: - FileStorage // class FileStorage<T: Codable> { private let fileURL: URL private lazy var decoder = JSONDecoder() private lazy var encoder = JSONEncoder() init(fileURL: URL) { self.fileURL = fileURL } /// Load an object /// func load() throws -> T? { let data = try Data(contentsOf: fileURL) return try decoder.decode(T.self, from: data) } /// Save an object /// func save(object: T) throws { let data = try encoder.encode(object) try data.write(to: fileURL) } } ```
/content/code_sandbox/Simplenote/Classes/FileStorage.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
145
```objective-c // // SPInteractivePushPopAnimationController.h // Simplenote // // Created by James Frost on 08/10/2015. // #import <UIKit/UIKit.h> @class SPInteractivePushPopAnimationController; @protocol SPInteractivePushViewControllerProvider <NSObject> - (UIViewController *)nextViewControllerForInteractivePush; - (BOOL)interactivePushPopAnimationControllerShouldBeginPush:(SPInteractivePushPopAnimationController *)controller touchPoint:(CGPoint)touchPoint; - (void)interactivePushPopAnimationControllerWillBeginPush:(SPInteractivePushPopAnimationController *)controller; @end @protocol SPInteractivePushViewControllerContent <NSObject> @end /** * @class SPInteractivePushPopAnimationController * @brief Allows the user to pan horizontally anywhere within the note editor to present * the Markdown preview (and swipe anywhere within the preview to return). */ @interface SPInteractivePushPopAnimationController : NSObject<UIViewControllerAnimatedTransitioning> /// Interactive transition for use by a `UINavigationControllerDelegate`. /// Currently used by `SPTransitionController` to make this animation interactive. @property (nonatomic, strong, readonly) UIPercentDrivenInteractiveTransition *interactiveTransition; @property (nonatomic, weak) UINavigationController *navigationController; @property (nonatomic) UINavigationControllerOperation navigationOperation; - (instancetype)initWithNavigationController:(UINavigationController *)navigationController; @end ```
/content/code_sandbox/Simplenote/Classes/SPInteractivePushPopAnimationController.h
objective-c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
275
```swift import UIKit // MARK: - TagViewDelegate // protocol TagViewDelegate: AnyObject { func tagView(_ tagView: TagView, wantsToCreateTagWithName name: String) func tagView(_ tagView: TagView, wantsToRemoveTagWithName name: String) func tagViewDidBeginEditing(_ tagView: TagView) func tagViewDidChange(_ tagView: TagView) } // MARK: - TagView // class TagView: UIView { private lazy var stackView: UIStackView = { let stackView = UIStackView() stackView.axis = .horizontal stackView.alignment = .fill stackView.distribution = .fill stackView.spacing = Constants.tagsStackViewSpacing return stackView }() private lazy var scrollView: UIScrollView = { let scrollView = UIScrollView() scrollView.translatesAutoresizingMaskIntoConstraints = false scrollView.scrollsToTop = false scrollView.alwaysBounceHorizontal = true scrollView.showsHorizontalScrollIndicator = false return scrollView }() private lazy var addTagField: SPTagEntryField = { let field = SPTagEntryField() field.delegate = self field.tagDelegate = self return field }() private var autohideDeleteButtonTimer: Timer? { didSet { oldValue?.invalidate() } } /// Delegate /// weak var delegate: TagViewDelegate? /// Keyboard appearance /// var keyboardAppearance: UIKeyboardAppearance { get { return addTagField.keyboardAppearance } set { addTagField.keyboardAppearance = newValue } } var addTagFieldText: String? { get { addTagField.text } set { addTagField.text = newValue } } var addTagFieldFrameInWindow: CGRect { var frame = addTagField.convert(addTagField.bounds, to: self) frame.origin.y = 0 frame.size.height = frame.size.height return convert(frame, to: nil) } override init(frame: CGRect) { super.init(frame: frame) configure() } required init?(coder: NSCoder) { super.init(coder: coder) configure() } /// Setup with a list of tag names /// func setup(withTagNames tagNames: [String]) { removeAllTags() for tagName in tagNames { add(tag: tagName) } } /// Add a tag with specified name /// func add(tag tagName: String) { stackView.addArrangedSubview(cell(for: tagName)) updateStackViewVisibility() } /// Remove a tag with specified name /// func remove(tag tagName: String) { guard let cell = tagCells.first(where: { $0.tagName == tagName }) else { return } cell.removeFromSuperview() updateStackViewVisibility() } override func endEditing(_ force: Bool) -> Bool { hideDeleteButton() return super.endEditing(force) } func scrollEntryFieldToVisible(animated: Bool) { guard !isShowingDeleteButton else { return } layoutIfNeeded() let addTagFieldFrame = addTagField.convert(addTagField.bounds, to: scrollView) scrollView.scrollRectToVisible(addTagFieldFrame.insetBy(dx: -Constants.wrappingStackViewMargins.right, dy: 0), animated: animated) } } // MARK: - Private // private extension TagView { func configure() { setupViewHierarchy() } func setupViewHierarchy() { setupHiddenCell() let wrappingStackView = UIStackView(arrangedSubviews: [stackView, addTagField]) wrappingStackView.axis = .horizontal wrappingStackView.alignment = .center wrappingStackView.distribution = .fill wrappingStackView.spacing = Constants.wrappingStackViewSpacing scrollView.addFillingSubview(wrappingStackView, edgeInsets: Constants.wrappingStackViewMargins) wrappingStackView.heightAnchor.constraint(equalTo: scrollView.heightAnchor).isActive = true addFillingSubview(scrollView) if UIApplication.isRTL { scrollView.transform = CGAffineTransform(rotationAngle: .pi) wrappingStackView.transform = CGAffineTransform(rotationAngle: .pi) } } /// Sets up hidden cell to make sure view has correct height even if there are no tags /// func setupHiddenCell() { let hiddenCell = TagViewCell(tagName: "A") hiddenCell.translatesAutoresizingMaskIntoConstraints = false hiddenCell.isHidden = true hiddenCell.isAccessibilityElement = false addSubview(hiddenCell) NSLayoutConstraint.activate([ hiddenCell.topAnchor.constraint(equalTo: topAnchor, constant: Constants.hiddenCellVerticalMargin), hiddenCell.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -Constants.hiddenCellVerticalMargin), hiddenCell.centerXAnchor.constraint(equalTo: centerXAnchor) ]) } func updateStackViewVisibility() { stackView.isHidden = stackView.arrangedSubviews.isEmpty } } // MARK: - Cells // private extension TagView { var tagCells: [TagViewCell] { return (stackView.arrangedSubviews as? [TagViewCell]) ?? [] } func cell(for tagName: String) -> TagViewCell { let cell = TagViewCell(tagName: tagName) cell.onTap = { [weak self, weak cell] in guard let self = self, let cell = cell else { return } self.toggleDeleteButton(for: cell) } cell.onDelete = { [weak self] in guard let self = self else { return } self.delegate?.tagView(self, wantsToRemoveTagWithName: tagName) } return cell } func removeAllTags() { for view in stackView.arrangedSubviews { view.removeFromSuperview() } updateStackViewVisibility() } } // MARK: - Editing // private extension TagView { var isShowingDeleteButton: Bool { tagCells.contains(where: { $0.isDeleteButtonVisible }) } func toggleDeleteButton(for cell: TagViewCell) { let newValue = !cell.isDeleteButtonVisible hideDeleteButton() cell.isDeleteButtonVisible = newValue if newValue { autohideDeleteButtonTimer = Timer.scheduledTimer(withTimeInterval: Constants.autohideDeleteButtonTimeout, repeats: false, block: { [weak self] (_) in self?.hideDeleteButton() }) } } func hideDeleteButton() { autohideDeleteButtonTimer = nil for cell in tagCells { cell.isDeleteButtonVisible = false } } } // MARK: - Tag processing // private extension TagView { func validateInput(_ textField: UITextField, range: NSRange, replacement: String) -> Bool { let text = (textField.text ?? "") guard let range = Range(range, in: text) else { return true } let validator = TagTextFieldInputValidator() let result = validator.validateInput(originalText: text, range: range, replacement: replacement) switch result { case .valid: return true case .endingWithDisallowedCharacter(let text): textField.text = text processTextInFieldToTag() return false case .invalid: return false } } func processTextInFieldToTag() { guard let tagName = addTagField.text, !tagName.isEmpty else { return } delegate?.tagView(self, wantsToCreateTagWithName: tagName) addTagField.text = "" scrollEntryFieldToVisible(animated: true) } } // MARK: - UITextFieldDelegate // extension TagView: UITextFieldDelegate { func textFieldDidBeginEditing(_ textField: UITextField) { hideDeleteButton() delegate?.tagViewDidBeginEditing(self) scrollEntryFieldToVisible(animated: true) } func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { return validateInput(textField, range: range, replacement: string) } func textFieldShouldReturn(_ textField: UITextField) -> Bool { processTextInFieldToTag() return false } func textFieldDidEndEditing(_ textField: UITextField) { hideDeleteButton() processTextInFieldToTag() } } // MARK: - SPTagEntryFieldDelegate // extension TagView: SPTagEntryFieldDelegate { func tagEntryFieldDidChange(_ tagTextField: SPTagEntryField!) { hideDeleteButton() DispatchQueue.main.async { self.scrollEntryFieldToVisible(animated: true) } delegate?.tagViewDidChange(self) } } // MARK: - Constants // private struct Constants { static let wrappingStackViewSpacing: CGFloat = 16 static let wrappingStackViewMargins = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20) static let tagsStackViewSpacing: CGFloat = 8 static let hiddenCellVerticalMargin: CGFloat = 8 static let autohideDeleteButtonTimeout: TimeInterval = 4.0 } ```
/content/code_sandbox/Simplenote/Classes/TagView.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
1,958
```swift import Foundation // MARK: - UIActivity <> WordPress iOS! // extension UIActivity.ActivityType { /// WordPress Draft Extension (AppStore) /// static var wordPressDraftAppStore: UIActivity.ActivityType { return UIActivity.ActivityType("org.wordpress.WordPressDraftAction") } /// WordPress Draft Extension (Internal Beta) /// static var wordPressDraftInternal: UIActivity.ActivityType { return UIActivity.ActivityType("org.wordpress.internal.WordPressDraftAction") } /// WordPress Share Extension (AppStore) /// static var wordPressShareAppStore: UIActivity.ActivityType { return UIActivity.ActivityType("org.wordpress.WordPressShare") } /// WordPress Share Extension (Internal Beta) /// static var wordPressShareInternal: UIActivity.ActivityType { return UIActivity.ActivityType("org.wordpress.internal.WordPressShare") } /// Indicates if a given UIActivity belongs to the WordPress iOS App /// var isWordPressActivity: Bool { let wordpressActivities: [UIActivity.ActivityType] = [ .wordPressDraftAppStore, .wordPressDraftInternal, .wordPressShareAppStore, .wordPressShareInternal ] return wordpressActivities.contains(self) } } ```
/content/code_sandbox/Simplenote/Classes/UIActivity+Simplenote.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
263
```objective-c // // SPSimperiumManager.h // Simplenote // // Created by Tom Witkin on 7/26/13. // #import <Foundation/Foundation.h> @class Note; @class Tag; NS_ASSUME_NONNULL_BEGIN @interface SPObjectManager : NSObject + (SPObjectManager *)sharedManager; - (NSArray<Note *> *)notes; - (NSArray<Tag *> *)tags; #pragma mark - Tags - (void)editTag:(Tag *)tag title:(NSString *)newTitle; - (BOOL)removeTagName:(NSString *)tagName; - (BOOL)removeTag:(Tag *)tag; - (Tag *)createTagFromString:(NSString *)tagName; - (BOOL)tagExists:(NSString *)tagName; - (Tag *)tagForName:(NSString *)tagName; - (void)moveTagFromIndex:(NSInteger)fromIndex toIndex:(NSInteger)toIndex; #pragma mark - Notes - (void)trashNote:(Note *)note; - (void)restoreNote:(Note *)note; - (void)permenentlyDeleteNote:(Note *)note; - (void)emptyTrash; #pragma mark - Updating Notes - (void)updateMarkdownState:(BOOL)markdown note:(Note *)note; - (void)updatePublishedState:(BOOL)published note:(Note *)note; - (void)updatePinnedState:(BOOL)pinned note:(Note *)note; #pragma mark - Sharing - (void)insertTagNamed:(NSString *)tagName note:(Note *)note; - (void)removeTagNamed:(NSString *)tagName note:(Note *)note; @end NS_ASSUME_NONNULL_END ```
/content/code_sandbox/Simplenote/Classes/SPObjectManager.h
objective-c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
337
```objective-c #import "NSString+Condensing.h" @implementation NSString (Condensing) - (NSString *)stringByReplacingNewlinesWithSpaces { if (self.length == 0) { return self; } // Newlines: \n *AND* \r's! NSMutableArray *components = [[self componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]] mutableCopy]; // Note: The following nukes everything that tests true for `isEquals`: Every single empty string is gone! [components removeObject:@""]; return [components componentsJoinedByString:@" "]; } @end ```
/content/code_sandbox/Simplenote/Classes/NSString+Condensing.m
objective-c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
124
```swift import Foundation import UIKit // MARK: - SPDiagnosticsViewController // class SPDiagnosticsViewController: UIViewController { /// Label: Title /// @IBOutlet private var titleLabel: UILabel! /// TextView: Details /// @IBOutlet private var detailsTextView: UITextView! /// Text to be presented /// var attributedText: NSAttributedString? // MARK: - Overridden Methods override func viewDidLoad() { super.viewDidLoad() setupTitleLabel() setupTextView() setupNavigationItem() } } // MARK: - Interface // private extension SPDiagnosticsViewController { func setupTitleLabel() { titleLabel.text = NSLocalizedString("Diagnostics", comment: "Title displayed in the extended diagnostics UI") } func setupTextView() { assert(attributedText != nil, "Missing Diagnostics Text") detailsTextView.attributedText = attributedText detailsTextView.backgroundColor = .white } func setupNavigationItem() { navigationItem.leftBarButtonItem = UIBarButtonItem(title: NSLocalizedString("Share", comment: "Share Action"), style: .plain, target: self, action: #selector(shareWasPressed)) navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(dismissWasPressed)) } } // MARK: - Actions // private extension SPDiagnosticsViewController { @IBAction func shareWasPressed() { guard let attributedText = attributedText else { fatalError() } let items = [attributedText.string] let excludedActivities: [UIActivity.ActivityType] = [.print, .message, .postToFacebook, .postToTwitter, .assignToContact, .airDrop] let activityViewController = UIActivityViewController(activityItems: items, applicationActivities: nil) activityViewController.excludedActivityTypes = excludedActivities present(activityViewController, animated: true) } @IBAction func dismissWasPressed() { dismiss(animated: true, completion: nil) } } ```
/content/code_sandbox/Simplenote/Classes/SPDiagnosticsViewController.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
422
```swift // // CSSearchableItem+Helpers.swift // Simplenote // // Created by Michal Kosmowski on 25/11/2016. // import Foundation import CoreSpotlight import MobileCoreServices import UniformTypeIdentifiers extension CSSearchableItemAttributeSet { convenience init(note: Note) { self.init(contentType: UTType.data) note.ensurePreviewStringsAreAvailable() title = note.titlePreview contentDescription = note.bodyPreview } } extension CSSearchableItem { convenience init(note: Note) { let attributeSet = CSSearchableItemAttributeSet(note: note) self.init(uniqueIdentifier: note.simperiumKey, domainIdentifier: "notes", attributeSet: attributeSet) } } extension CSSearchableIndex { // MARK: - Index Notes @objc func indexSpotlightItems(in context: NSManagedObjectContext) { guard Options.shared.indexNotesInSpotlight else { return } context.perform { if let deleted = context.fetchObjects(forEntityName: "Note", with: NSPredicate(format: "deleted == YES")) as? [Note] { self.deleteSearchableNotes(deleted) } if let notes = context.fetchObjects(forEntityName: "Note", with: NSPredicate(format: "deleted == NO")) as? [Note] { self.indexSearchableNotes(notes) } } } @objc func indexSearchableNote(_ note: Note) { guard Options.shared.indexNotesInSpotlight else { return } let item = CSSearchableItem(note: note) indexSearchableItems([item]) { error in if let error = error { NSLog("Couldn't index note in spotlight: \(error.localizedDescription)") } } } @objc func indexSearchableNotes(_ notes: [Note]) { guard Options.shared.indexNotesInSpotlight else { return } let items = notes.map { return CSSearchableItem(note: $0) } indexSearchableItems(items) { error in if let error = error { NSLog("Couldn't index notes in spotlight: \(error.localizedDescription)") } } } @objc func deleteSearchableNote(_ note: Note) { deleteSearchableNotes([note]) } @objc func deleteSearchableNotes(_ notes: [Note]) { let ids = notes.map { return $0.simperiumKey! } deleteSearchableItems(withIdentifiers: ids) { error in if let error = error { NSLog("Couldn't delete notes from spotlight index: \(error.localizedDescription)") } } } } ```
/content/code_sandbox/Simplenote/Classes/CSSearchable+Helpers.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
577
```swift import Foundation // MARK: - NotesListSection // struct NotesListSection { /// Section Title /// let title: String? /// Section Objects /// let objects: [Any] /// Returns the number of Objects in the current section /// var numberOfObjects: Int { objects.count } var displaysTitle: Bool { title != nil && numberOfObjects > 0 } } ```
/content/code_sandbox/Simplenote/Classes/NotesListSection.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
93
```swift import Foundation // MARK: - UITableView Simplenote Methods // extension UITableView { /// Applies Simplenote's Style for Grouped TableVIews /// @objc func applySimplenoteGroupedStyle() { backgroundColor = .simplenoteTableViewBackgroundColor separatorColor = .simplenoteDividerColor } /// Applies Simplenote's Style for Plain TableVIews /// @objc func applySimplenotePlainStyle() { backgroundColor = .simplenoteBackgroundColor separatorColor = .simplenoteDividerColor } /// Scrolls to the top of the TableView /// @objc(scrollToTopWithAnimation:) func scrollToTop(animated: Bool) { var newOffset = contentOffset newOffset.y = adjustedContentInset.top * -1 setContentOffset(newOffset, animated: animated) } /// Returns a cell of a given kind, to be displayed at the specified IndexPath /// func dequeueReusableCell<T: UITableViewCell>(ofType type: T.Type, for indexPath: IndexPath) -> T { guard let cell = dequeueReusableCell(withIdentifier: T.reuseIdentifier, for: indexPath) as? T else { fatalError() } return cell } /// Returns a Header instance of the specified kind /// func dequeueReusableHeaderFooterView<T: UITableViewHeaderFooterView>(ofType type: T.Type) -> T? { return dequeueReusableHeaderFooterView(withIdentifier: T.reuseIdentifier) as? T } } // MARK: - Navigation // extension UITableView { /// Returns first index path from the first non-empty section /// var firstIndexPath: IndexPath? { let indexPath = IndexPath(row: 0, section: 0) if numberOfRows(inSection: 0) == 0 { return self.indexPath(after: indexPath) } return indexPath } /// Returns index path after currently selected index path /// var nextIndexPath: IndexPath? { guard let indexPath = indexPathForSelectedRow else { return nil } return self.indexPath(after: indexPath) } /// Returns index path before currently selected index path /// var prevIndexPath: IndexPath? { guard let indexPath = indexPathForSelectedRow else { return nil } return self.indexPath(before: indexPath) } /// Selects row after currently selected row or first row if no row is currently selected /// func selectNextRow() { guard let indexPath = (indexPathForSelectedRow != nil ? nextIndexPath : firstIndexPath) else { return } deselectSelectedRow() selectRow(at: indexPath, animated: false, scrollPosition: .none) scrollRectToVisible(rectForRow(at: indexPath), animated: false) } /// Selects row before currently selected row or first row if no row is currently selected /// func selectPrevRow() { guard let indexPath = prevIndexPath ?? firstIndexPath else { return } deselectSelectedRow() selectRow(at: indexPath, animated: false, scrollPosition: .none) scrollRectToVisible(rectForRow(at: indexPath), animated: false) } /// Calls `didSelectRow` for a currently selected row /// func executeSelection() { guard let indexPath = indexPathForSelectedRow else { return } delegate?.tableView?(self, didSelectRowAt: indexPath) } /// Deselects selected row if any /// @objc(deselectSelectedRowAnimated:) func deselectSelectedRow(animated: Bool = false) { guard let indexPath = indexPathForSelectedRow else { return } deselectRow(at: indexPath, animated: animated) } func deselectSelectedRows(animated: Bool = false) { guard let selectedIndicies = indexPathsForVisibleRows else { return } for indexPath in selectedIndicies { deselectRow(at: indexPath, animated: animated) } } func selectAllRows(inSection section: Int, animated: Bool) { forEachIndexPath(in: section) { indexPath in selectRow(at: indexPath, animated: animated, scrollPosition: .none) } } func deselectAllRows(inSection section: Int, animated: Bool) { forEachIndexPath(in: section) { indexPath in deselectRow(at: indexPath, animated: animated) } } func forEachIndexPath(in section: Int, doAction action: (IndexPath)-> Void) { let rows = numberOfRows(inSection: section) for row in Int.zero..<rows { let indexpath = IndexPath(row: row, section: section) action(indexpath) } } } // MARK: - Navigation (Private) // private extension UITableView { func indexPath(after prevIndexPath: IndexPath) -> IndexPath? { var row = prevIndexPath.row var section = prevIndexPath.section while true { row += 1 if row >= numberOfRows(inSection: section) { section += 1 if section >= numberOfSections { return nil } row = -1 } else { return IndexPath(row: row, section: section) } } } func indexPath(before nextIndexPath: IndexPath) -> IndexPath? { var row = nextIndexPath.row var section = nextIndexPath.section while true { if row == 0 { if section == 0 { return nil } section -= 1 row = numberOfRows(inSection: section) } else { return IndexPath(row: row - 1, section: section) } } } } ```
/content/code_sandbox/Simplenote/Classes/UITableView+Simplenote.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
1,203
```swift import Foundation import UIKit import SafariServices import SwiftUI import SimplenoteEndpoints // MARK: - SPAuthViewController // class SPAuthViewController: UIViewController { /// # Links to the StackView and the container view /// @IBOutlet private var stackViewTopConstraint: NSLayoutConstraint! /// # StackView: Contains the entire UI /// @IBOutlet private var stackView: UIStackView! /// # Header: Container View /// @IBOutlet private var headerContainerView: UIView! /// # Header: Title Label /// @IBOutlet private var headerLabel: SPLabel! /// # Email: Input Field /// @IBOutlet private var emailInputView: SPTextInputView! { didSet { emailInputView.keyboardType = .emailAddress emailInputView.placeholder = AuthenticationStrings.emailPlaceholder emailInputView.returnKeyType = .next emailInputView.rightViewMode = .always emailInputView.textColor = .simplenoteGray80Color emailInputView.delegate = self emailInputView.textContentType = .username } } /// # Email: Warning Label /// @IBOutlet private var emailWarningLabel: SPLabel! { didSet { emailWarningLabel.textInsets = AuthenticationConstants.warningInsets emailWarningLabel.textColor = .simplenoteRed60Color emailWarningLabel.isHidden = true } } /// # Password: Input Field /// @IBOutlet private var passwordInputView: SPTextInputView! { didSet { passwordInputView.isSecureTextEntry = true passwordInputView.placeholder = AuthenticationStrings.passwordPlaceholder passwordInputView.rightViewInsets = AuthenticationConstants.accessoryViewInsets passwordInputView.passwordRules = UITextInputPasswordRules(descriptor: SimplenoteConstants.passwordRules) passwordInputView.returnKeyType = .done passwordInputView.rightView = revealPasswordButton passwordInputView.rightViewMode = .always passwordInputView.textColor = .simplenoteGray80Color passwordInputView.delegate = self passwordInputView.textContentType = .password } } /// # Password: Warning Label /// @IBOutlet private var passwordWarningLabel: SPLabel! { didSet { passwordWarningLabel.textInsets = AuthenticationConstants.warningInsets passwordWarningLabel.textColor = .simplenoteRed60Color passwordWarningLabel.isHidden = true } } /// # Code: Input Field /// @IBOutlet private var codeInputView: SPTextInputView! { didSet { codeInputView.placeholder = AuthenticationStrings.codePlaceholder codeInputView.passwordRules = UITextInputPasswordRules(descriptor: SimplenoteConstants.passwordRules) codeInputView.returnKeyType = .done codeInputView.textColor = .simplenoteGray80Color codeInputView.delegate = self codeInputView.textContentType = .oneTimeCode } } /// # Code: Warning Label /// @IBOutlet private var codeWarningLabel: SPLabel! { didSet { codeWarningLabel.textInsets = AuthenticationConstants.warningInsets codeWarningLabel.textColor = .simplenoteRed60Color codeWarningLabel.isHidden = true } } /// # Primary Action: LogIn / SignUp /// @IBOutlet private var primaryActionButton: SPSquaredButton! { didSet { primaryActionButton.setTitleColor(.white, for: .normal) primaryActionButton.accessibilityIdentifier = "Main Action" } } /// # Primary Action Spinner! /// @IBOutlet private var primaryActionSpinner: UIActivityIndicatorView! { didSet { primaryActionSpinner.style = .medium primaryActionSpinner.color = .white } } /// # Forgot Password Action /// @IBOutlet private var secondaryActionButton: UIButton! { didSet { secondaryActionButton.setTitleColor(.simplenoteBlue60Color, for: .normal) secondaryActionButton.titleLabel?.textAlignment = .center secondaryActionButton.titleLabel?.numberOfLines = 0 } } /// # Reveal Password Button /// private lazy var revealPasswordButton: UIButton = { let selected = UIImage.image(name: .visibilityOn) let button = UIButton(type: .custom) button.tintColor = .simplenoteGray50Color button.addTarget(self, action: #selector(revealPasswordWasPressed), for: [.touchDown]) button.setImage(.image(name: .visibilityOff), for: .normal) button.setImage(selected, for: .highlighted) button.setImage(selected, for: .selected) button.sizeToFit() return button }() /// # Actions Separator: Container /// @IBOutlet private var actionsSeparator: UIView! /// # Tertiary Separator: Label (Or) /// @IBOutlet private var actionsSeparatorLabel: UILabel! { didSet { actionsSeparatorLabel.text = AuthenticationStrings.separatorText } } /// # Tertiary Action: WPCOM SSO /// @IBOutlet private var tertiaryActionButton: SPSquaredButton! { didSet { tertiaryActionButton.setTitleColor(.white, for: .normal) tertiaryActionButton.backgroundColor = .simplenoteWPBlue50Color } } /// # Tertiary Action: /// @IBOutlet private var quaternaryActionButton: SPSquaredButton! { didSet { quaternaryActionButton.setTitleColor(.black, for: .normal) quaternaryActionButton.backgroundColor = .clear quaternaryActionButton.layer.borderWidth = 1 quaternaryActionButton.layer.borderColor = UIColor.black.cgColor } } /// # All of the Visible InputView(s) /// private var visibleInputViews: [SPTextInputView] { [emailInputView, passwordInputView, codeInputView].filter { inputView in inputView.isHidden == false } } /// # All of the Action Views /// private var allActionViews: [UIButton] { [primaryActionButton, secondaryActionButton, tertiaryActionButton, quaternaryActionButton] } /// # Simperium's Authenticator Instance /// private let controller: SPAuthHandler /// # Simperium's Validator /// private lazy var validator = AuthenticationValidator() /// # Indicates if we've got valid Credentials. Doesn't display any validation warnings onscreen /// private var isInputValid: Bool { performInputElementsValidation().values.allSatisfy { result in result == .success } } /// # Returns the EmailInputView's Text: When empty this getter returns an empty string, instead of nil /// private var email: String { state.username } /// # Returns the PasswordInputView's Text: When empty this getter returns an empty string, instead of nil /// private var password: String { state.password } /// Indicates if we must nuke the Password Field's contents whenever the App becomes active /// private var mustResetPasswordField = false /// # Authentication Mode: Signup / Login with Password / Login with Link /// private let mode: AuthenticationMode /// # State: Allows us to preserve State, when dealing with a multi staged flow /// private var state: AuthenticationState { didSet { ensureStylesMatchValidationState() ensureWarningsAreDismissedWhenNeeded() } } /// Indicates if the Extended Debug Mode is enabled /// var debugEnabled = false /// NSCodable Required Initializer /// required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } /// Designated Initializer /// init(controller: SPAuthHandler, mode: AuthenticationMode = .requestLoginCode, state: AuthenticationState = .init()) { self.controller = controller self.mode = mode self.state = state super.init(nibName: nil, bundle: nil) } // MARK: - Overridden Methods override func viewDidLoad() { super.viewDidLoad() setupNavigationController() startListeningToNotifications() refreshHeaderView() refreshInputViews() refreshActionViews() reloadInputViewsFromState() // hiding text from back button navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) ensureStylesMatchValidationState() ensureNavigationBarIsVisible() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // Note: running becomeFirstResponder in `viewWillAppear` has the weird side effect of breaking caret // repositioning in the Text Field. Seriously. // Ref. path_to_url // visibleInputViews.first?.becomeFirstResponder() } } // MARK: - Actions // extension SPAuthViewController { @IBAction func revealPasswordWasPressed() { let isPasswordVisible = !revealPasswordButton.isSelected revealPasswordButton.isSelected = isPasswordVisible passwordInputView.isSecureTextEntry = !isPasswordVisible } } // MARK: - Interface // private extension SPAuthViewController { func setupNavigationController() { title = mode.title navigationController?.navigationBar.applyLightStyle() } func startListeningToNotifications() { NotificationCenter.default.addObserver(self, selector: #selector(applicationDidBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil) } func ensureNavigationBarIsVisible() { navigationController?.setNavigationBarHidden(false, animated: true) } func refreshHeaderView() { let headerText = mode.buildHeaderText(email: email) headerLabel.attributedText = headerText headerContainerView.isHidden = headerText == nil } func refreshInputViews() { let inputElements = mode.inputElements emailInputView.isHidden = !inputElements.contains(.username) passwordInputView.isHidden = !inputElements.contains(.password) codeInputView.isHidden = !inputElements.contains(.code) actionsSeparator.isHidden = !inputElements.contains(.actionSeparator) } func refreshActionViews() { let viewMap: [AuthenticationActionName: UIButton] = [ .primary: primaryActionButton, .secondary: secondaryActionButton, .tertiary: tertiaryActionButton, .quaternary: quaternaryActionButton ] for actionView in allActionViews { actionView.isHidden = true } for descriptor in mode.actions { guard let actionView = viewMap[descriptor.name] else { assertionFailure() continue } if let title = descriptor.text { actionView.setTitle(title, for: .normal) } if let attributedTitle = descriptor.attributedText { actionView.setAttributedTitle(attributedTitle, for: .normal) } actionView.addTarget(self, action: descriptor.selector, for: .touchUpInside) actionView.isHidden = false } } func reloadInputViewsFromState() { emailInputView.text = state.username passwordInputView.text = state.password codeInputView.text = state.code } func ensureStylesMatchValidationState() { primaryActionButton.backgroundColor = isInputValid ? .simplenoteBlue50Color : .simplenoteGray20Color } @objc func applicationDidBecomeActive() { ensurePasswordFieldIsReset() } func ensurePasswordFieldIsReset() { guard mustResetPasswordField else { return } passwordInputView.text = nil passwordInputView.becomeFirstResponder() } private func lockdownInterface() { view.endEditing(true) view.isUserInteractionEnabled = false primaryActionSpinner.startAnimating() } private func unlockInterface() { view.isUserInteractionEnabled = true primaryActionSpinner.stopAnimating() } } // MARK: - Actions // extension SPAuthViewController { /// Whenever the input is Valid, we'll perform the Primary Action /// func performPrimaryActionIfPossible() { guard ensureWarningsAreOnScreenWhenNeeded() else { return } guard let primaryActionDescriptor = mode.actions.first(where: { $0.name == .primary}) else { assertionFailure() return } perform(primaryActionDescriptor.selector) } @IBAction func performLogInWithPassword() { guard ensureWarningsAreOnScreenWhenNeeded() else { return } if mustUpgradePasswordStrength() { performCredentialsValidation() return } performSimperiumAuthentication() } @IBAction func requestLogInCode() { guard ensureWarningsAreOnScreenWhenNeeded() else { return } Task { @MainActor in await requestLogInCodeAsync() } } @MainActor private func requestLogInCodeAsync() async { lockdownInterface() do { try await controller.requestLoginEmail(username: email) self.presentCodeInterface() SPTracker.trackLoginLinkRequested() } catch SPAuthError.tooManyAttempts { self.presentPasswordInterfaceWithRateLimitingHeader() } catch { let error = error as? SPAuthError ?? .generic self.handleError(error: error) } self.unlockInterface() } /// Requests a new Login Code, without pushing any secondary UI on success /// @IBAction func requestLogInCodeAndDontPush() { Task { @MainActor in await self.requestLogInCodeAndDontPushAsync() } } /// Requests a new Login Code, without pushing any secondary UI on success. Asynchronous API! /// @MainActor private func requestLogInCodeAndDontPushAsync() async { do { try await controller.requestLoginEmail(username: email) } catch { let error = error as? SPAuthError ?? .generic self.handleError(error: error) } SPTracker.trackLoginLinkRequested() } @IBAction func performLogInWithCode() { guard ensureWarningsAreOnScreenWhenNeeded() else { return } Task { @MainActor in lockdownInterface() do { try await controller.loginWithCode(username: state.username, code: state.code) SPTracker.trackLoginLinkConfirmationSuccess() } catch { /// Errors will always be of the `SPAuthError` type. Let's switch to Typed Errors, as soon as we migrate over to Xcode 16 let error = error as? SPAuthError ?? .generic self.handleError(error: error) SPTracker.trackLoginLinkConfirmationFailure() } unlockInterface() } } @IBAction func performLogInWithWPCOM() { WPAuthHandler.presentWordPressSSO(from: self) } @IBAction func performSignUp() { guard ensureWarningsAreOnScreenWhenNeeded() else { return } lockdownInterface() controller.signupWithCredentials(username: email) { [weak self] error in guard let self = self else { return } if let error = error { self.handleError(error: error) } else { self.presentSignupVerification() } self.unlockInterface() } } @IBAction func presentPasswordReset() { controller.presentPasswordReset(from: self, username: email) } @IBAction func presentTermsOfService() { guard let targetURL = URL(string: kSimperiumTermsOfServiceURL) else { return } let safariViewController = SFSafariViewController(url: targetURL) safariViewController.modalPresentationStyle = .overFullScreen present(safariViewController, animated: true, completion: nil) } @IBAction func presentPasswordInterface() { presentPasswordInterfaceWithHeader(header: AuthenticationStrings.loginWithEmailEmailHeader) } @IBAction func presentPasswordInterfaceWithRateLimitingHeader() { presentPasswordInterfaceWithHeader(header: AuthenticationStrings.loginWithEmailLimitHeader) } @IBAction func presentPasswordInterfaceWithHeader(header: String?) { let viewController = SPAuthViewController(controller: controller, mode: .loginWithPassword(header: header), state: state) navigationController?.pushViewController(viewController, animated: true) } } // MARK: - Navigation Helpers // private extension SPAuthViewController { func presentSignupVerification() { let viewController = SignupVerificationViewController(email: email) viewController.title = title navigationController?.pushViewController(viewController, animated: true) } func presentCodeInterface() { let viewController = SPAuthViewController(controller: controller, mode: .loginWithCode, state: state) navigationController?.pushViewController(viewController, animated: true) } } // MARK: - Simperium Services // private extension SPAuthViewController { func performCredentialsValidation() { lockdownInterface() controller.validateWithCredentials(username: email, password: password) { error in if let error = error { self.handleError(error: error) } else { self.presentPasswordResetRequiredAlert(email: self.email) } self.unlockInterface() } } func performSimperiumAuthentication() { lockdownInterface() controller.loginWithCredentials(username: email, password: password) { error in if let error = error { self.handleError(error: error) } else { SPTracker.trackUserSignedIn() } self.unlockInterface() } } } // MARK: - Password Reset Flow // private extension SPAuthViewController { func presentPasswordResetRequiredAlert(email: String) { guard let resetURL = URL(string: SimplenoteConstants.resetPasswordURL + email) else { fatalError() } let alertController = UIAlertController(title: PasswordInsecureString.title, message: PasswordInsecureString.message, preferredStyle: .alert) alertController.addCancelActionWithTitle(PasswordInsecureString.cancel) alertController.addDefaultActionWithTitle(PasswordInsecureString.reset) { [weak self] _ in self?.mustResetPasswordField = true UIApplication.shared.open(resetURL, options: [:], completionHandler: nil) } present(alertController, animated: true, completion: nil) } } // MARK: - Error Handling // private extension SPAuthViewController { func handleError(error: SPAuthError) { switch error { case .signupUserAlreadyExists: presentUserAlreadyExistsError(error: error) case .compromisedPassword: presentPasswordCompromisedError(error: error) case .unverifiedEmail: presentUserUnverifiedError(error: error, email: email) case .requestNotFound: presentLoginCodeExpiredError() case .unknown(let statusCode, let response, let error) where debugEnabled: let details = NSAttributedString.stringFromNetworkError(statusCode: statusCode, response: response, error: error) presentDebugDetails(details: details) default: presentGenericError(error: error) } } func presentUserAlreadyExistsError(error: SPAuthError) { let alertController = UIAlertController(title: error.title, message: error.message, preferredStyle: .alert) alertController.addCancelActionWithTitle(AuthenticationStrings.cancelActionText) alertController.addDefaultActionWithTitle(AuthenticationStrings.loginActionText) { _ in self.attemptLoginWithCurrentCredentials() } present(alertController, animated: true, completion: nil) } func presentPasswordCompromisedError(error: SPAuthError) { let alertController = UIAlertController(title: error.title, message: error.message, preferredStyle: .alert) alertController.addDefaultActionWithTitle(AuthenticationStrings.compromisedAlertReset) { _ in self.presentPasswordReset() } alertController.addCancelActionWithTitle(AuthenticationStrings.compromisedAlertCancel) present(alertController, animated: true, completion: nil) } func presentLoginCodeExpiredError() { let alertController = UIAlertController.buildLoginCodeNotFoundAlert { self.navigationController?.popViewController(animated: true) } present(alertController, animated: true, completion: nil) } func presentUserUnverifiedError(error: SPAuthError, email: String) { let alertController = UIAlertController(title: error.title, message: error.message, preferredStyle: .alert) alertController.addCancelActionWithTitle(AuthenticationStrings.unverifiedCancelText) alertController.addDefaultActionWithTitle(AuthenticationStrings.unverifiedActionText) { [weak self] _ in let spinnerVC = SpinnerViewController() self?.present(spinnerVC, animated: false, completion: nil) AccountRemote().verify(email: email) { result in spinnerVC.dismiss(animated: false, completion: nil) var alert: UIAlertController switch result { case .success: alert = UIAlertController.dismissableAlert(title: AuthenticationStrings.verificationSentTitle, message: String(format: AuthenticationStrings.verificationSentTemplate, email)) case .failure: alert = UIAlertController.dismissableAlert(title: AuthenticationStrings.unverifiedErrorTitle, message: AuthenticationStrings.unverifiedErrorMessage) } self?.present(alert, animated: true, completion: nil) } } present(alertController, animated: true, completion: nil) } func presentDebugDetails(details: NSAttributedString) { let supportViewController = SPDiagnosticsViewController() supportViewController.attributedText = details let navigationController = SPNavigationController(rootViewController: supportViewController) navigationController.modalPresentationStyle = .formSheet present(navigationController, animated: true, completion: nil) } func presentGenericError(error: SPAuthError) { let alertController = UIAlertController(title: error.title, message: error.message, preferredStyle: .alert) alertController.addDefaultActionWithTitle(AuthenticationStrings.acceptActionText) present(alertController, animated: true, completion: nil) } func attemptLoginWithCurrentCredentials() { guard let navigationController = navigationController else { fatalError() } // Prefill the LoginViewController let loginViewController = SPAuthViewController(controller: controller, mode: .loginWithPassword(), state: state) loginViewController.loadViewIfNeeded() // Swap the current VC var updatedHierarchy = navigationController.viewControllers.filter { ($0 is SPAuthViewController) == false } updatedHierarchy.append(loginViewController) navigationController.setViewControllers(updatedHierarchy, animated: true) } } // MARK: - Warning Labels // private extension SPAuthViewController { func displayEmailValidationWarning(_ string: String) { emailWarningLabel.text = string refreshEmailInput(inErrorState: true) } func displayPasswordValidationWarning(_ string: String) { passwordWarningLabel.text = string refreshPasswordInput(inErrorState: true) } func displayCodeValidationWarning(_ string: String) { codeWarningLabel.text = string refreshCodeInput(inErrorState: true) } func dismissEmailValidationWarning() { refreshEmailInput(inErrorState: false) } func dismissPasswordValidationWarning() { refreshPasswordInput(inErrorState: false) } func dismissCodeValidationWarning() { refreshCodeInput(inErrorState: false) } func refreshEmailInput(inErrorState: Bool) { emailWarningLabel.animateVisibility(isHidden: !inErrorState) emailInputView.inErrorState = inErrorState } func refreshPasswordInput(inErrorState: Bool) { passwordWarningLabel.animateVisibility(isHidden: !inErrorState) passwordInputView.inErrorState = inErrorState } func refreshCodeInput(inErrorState: Bool) { codeWarningLabel.animateVisibility(isHidden: !inErrorState) codeInputView.inErrorState = inErrorState } } // MARK: - Validation // private extension SPAuthViewController { /// When we're in `.login` mode, password requirements are relaxed (since we must allow users with old passwords to sign in). /// That's where the `validationStyle` comes in. /// func performInputElementsValidation() -> [AuthenticationInputElements: AuthenticationValidator.Result] { var result = [AuthenticationInputElements: AuthenticationValidator.Result]() if mode.inputElements.contains(.username) { result[.username] = validator.performUsernameValidation(username: email) } if mode.inputElements.contains(.password) { result[.password] = validator.performPasswordValidation(username: email, password: password, style: mode.validationStyle) } if mode.inputElements.contains(.code) { result[.code] = validator.performCodeValidation(code: state.code) } return result } /// Whenever we're in `.login` mode, and the password is valid in `.legacy` terms (but invalid in `.strong` mode), we must request the /// user to reset the password associated to his/her account. /// func mustUpgradePasswordStrength() -> Bool { validator.performPasswordValidation(username: email, password: password, style: .strong) != .success } /// Validates all of the Input Fields, and presents warnings accordingly. /// - Returns true: When all validations are passed /// func ensureWarningsAreOnScreenWhenNeeded() -> Bool { let validationMap = performInputElementsValidation() if let result = validationMap[.username], result != .success { displayEmailValidationWarning(result.description) } if let result = validationMap[.password], result != .success { displayPasswordValidationWarning(result.description) } if let result = validationMap[.code], result != .success { displayCodeValidationWarning(result.description) } return validationMap.values.allSatisfy { result in result == .success } } /// Validates all of the Input Fields, and dismisses validation warnings, when possible /// func ensureWarningsAreDismissedWhenNeeded() { let validationMap = performInputElementsValidation() if validationMap[.username] == .success { dismissEmailValidationWarning() } if validationMap[.password] == .success { dismissPasswordValidationWarning() } if validationMap[.code] == .success { dismissCodeValidationWarning() } } } // MARK: - UITextFieldDelegate Conformance // extension SPAuthViewController: SPTextInputViewDelegate { func textInputDidChange(_ textInput: SPTextInputView) { switch textInput { case emailInputView: state.username = textInput.text ?? "" case passwordInputView: state.password = textInput.text ?? "" case codeInputView: state.code = textInput.text ?? "" default: break } } func textInputShouldReturn(_ textInput: SPTextInputView) -> Bool { performPrimaryActionIfPossible() return false } func textInput(_ textInput: SPTextInputView, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { guard textInput == codeInputView else { return true } let maxLength = 6 let currentString = (textInput.text ?? "") as NSString let newString = currentString.replacingCharacters(in: range, with: string) return newString.count <= maxLength } } // MARK: - Authentication Strings // private enum AuthenticationStrings { static let separatorText = NSLocalizedString("Or", comment: "Or, used as a separator between Actions") static let emailPlaceholder = NSLocalizedString("Email", comment: "Email TextField Placeholder") static let passwordPlaceholder = NSLocalizedString("Password", comment: "Password TextField Placeholder") static let codePlaceholder = NSLocalizedString("Code", comment: "Code TextField Placeholder") static let acceptActionText = NSLocalizedString("Accept", comment: "Accept Action") static let cancelActionText = NSLocalizedString("Cancel", comment: "Cancel Action") static let loginActionText = NSLocalizedString("Log In", comment: "Log In Action") static let loginWithEmailEmailHeader = NSLocalizedString("Enter the password for the account {{EMAIL}}", comment: "Header for Login With Password. Please preserve the {{EMAIL}} substring") static let loginWithEmailLimitHeader = NSLocalizedString("Log in with email failed, please enter your password", comment: "Header for Enter Password UI, when the user performed too many requests") static let compromisedAlertCancel = NSLocalizedString("Cancel", comment: "Cancel action for password alert") static let compromisedAlertReset = NSLocalizedString("Change Password", comment: "Change password action") static let unverifiedCancelText = NSLocalizedString("Ok", comment: "Email unverified alert dismiss") static let unverifiedActionText = NSLocalizedString("Resend Verification Email", comment: "Send email verificaiton action") static let unverifiedErrorTitle = NSLocalizedString("Request Error", comment: "Request error alert title") static let unverifiedErrorMessage = NSLocalizedString("There was an preparing your verification email, please try again later", comment: "Request error alert message") static let verificationSentTitle = NSLocalizedString("Check your Email", comment: "Vefification sent alert title") static let verificationSentTemplate = NSLocalizedString("Weve sent a verification email to %1$@. Please check your inbox and follow the instructions.", comment: "Confirmation that an email has been sent") } // MARK: - PasswordInsecure Alert Strings // private enum PasswordInsecureString { static let cancel = NSLocalizedString("Cancel", comment: "Cancel Action") static let reset = NSLocalizedString("Reset", comment: "Reset Action") static let title = NSLocalizedString("Reset Required", comment: "Password Reset Required Alert Title") static let message = [ NSLocalizedString("Your password is insecure and must be reset. The password requirements are:", comment: "Password Requirements: Title"), String.newline, NSLocalizedString("- Password cannot match email", comment: "Password Requirement: Email Match"), NSLocalizedString("- Minimum of 8 characters", comment: "Password Requirement: Length"), NSLocalizedString("- Neither tabs nor newlines are allowed", comment: "Password Requirement: Special Characters") ].joined(separator: .newline) } // MARK: - Authentication Constants // private enum AuthenticationConstants { static let accessoryViewInsets = NSDirectionalEdgeInsets(top: .zero, leading: 16, bottom: .zero, trailing: 16) static let warningInsets = UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 0) } ```
/content/code_sandbox/Simplenote/Classes/SPAuthViewController.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
6,471
```swift import UIKit // MARK: - TagViewCell // class TagViewCell: RoundedView { private var stackViewConstraints: EdgeConstraints! private let stackView: UIStackView = { let stackView = UIStackView() stackView.alignment = .center stackView.distribution = .fill stackView.axis = .horizontal stackView.spacing = Constants.stackViewSpacing return stackView }() private let titleLabel: UILabel = { let label = UILabel() label.font = UIFont.preferredFont(for: .subheadline, weight: .medium) label.textAlignment = .center return label }() private let deleteButton: UIButton = { let button = RoundedCrossButton() button.style = .tagPill button.isUserInteractionEnabled = false button.contentMode = .scaleAspectFit NSLayoutConstraint.activate([ button.widthAnchor.constraint(equalToConstant: Constants.deleteButtonSideSize), button.heightAnchor.constraint(equalToConstant: Constants.deleteButtonSideSize) ]) return button }() /// Tag name /// let tagName: String /// Is delete button visible? /// var isDeleteButtonVisible: Bool { get { return !deleteButton.isHidden } set { deleteButton.isHidden = !newValue updateStackViewConstraints() } } /// Callback is invoked when user taps on the cell /// var onTap: (() -> Void)? /// Calback is invoked when user taps on delete button /// var onDelete: (() -> Void)? /// Init with tag name /// init(tagName: String) { self.tagName = tagName super.init(frame: .zero) configure() } required init?(coder: NSCoder) { fatalError() } } // MARK: - Private // private extension TagViewCell { func configure() { deleteButton.isHidden = true setupViewHierarchy() setupMinConstraints() refreshStyle() setupLabels() setupGestureRecognizer() setupAccessibility() } func setupViewHierarchy() { stackView.addArrangedSubview(titleLabel) stackView.addArrangedSubview(deleteButton) stackViewConstraints = addFillingSubview(stackView) updateStackViewConstraints() } func setupMinConstraints() { let minHeight = Constants.marginsWhenDeleteIsVisible.top + Constants.deleteButtonSideSize + Constants.marginsWhenDeleteIsVisible.bottom NSLayoutConstraint.activate([ heightAnchor.constraint(greaterThanOrEqualToConstant: minHeight), widthAnchor.constraint(greaterThanOrEqualTo: heightAnchor, multiplier: Constants.widthConstraintMultiplier) ]) } func setupLabels() { titleLabel.text = tagName } func setupGestureRecognizer() { let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTap(_:))) addGestureRecognizer(tapGestureRecognizer) } func refreshStyle() { backgroundColor = .simplenoteTagPillBackgroundColor titleLabel.textColor = .simplenoteTagPillTextColor } func updateStackViewConstraints() { let edgeInsets = isDeleteButtonVisible ? Constants.marginsWhenDeleteIsVisible : Constants.margins stackViewConstraints.update(with: edgeInsets) } @objc func handleTap(_ gestureRecognizer: UIGestureRecognizer) { if isDeleteButtonVisible { let point = gestureRecognizer.location(in: deleteButton) let insetBounds = deleteButton.bounds.insetBy(dx: Constants.deleteButtonHitAreaInset, dy: Constants.deleteButtonHitAreaInset) if insetBounds.contains(point) { onDelete?() return } } onTap?() } } // MARK: - Accessibility // extension TagViewCell { private func setupAccessibility() { isAccessibilityElement = true accessibilityLabel = tagName let deleteAction = UIAccessibilityCustomAction(name: Localization.removeTagHint, target: self, selector: #selector(accessibilityRemoveTag)) accessibilityCustomActions = [deleteAction] } @objc private func accessibilityRemoveTag() -> Bool { onDelete?() return true } } // MARK: - Constants // private struct Constants { static let margins = UIEdgeInsets(top: 5, left: 12, bottom: 5, right: 12) static let marginsWhenDeleteIsVisible = UIEdgeInsets(top: 5, left: 12, bottom: 5, right: 5) static let stackViewSpacing: CGFloat = 8 static let widthConstraintMultiplier: CGFloat = 1.3 static let deleteButtonSideSize: CGFloat = 20 static let deleteButtonHitAreaInset: CGFloat = -10 } // MARK: - Localization // private struct Localization { static let removeTagHint = NSLocalizedString("Remove tag from the current note", comment: "Accessibility hint for removing a tag from the current note") } ```
/content/code_sandbox/Simplenote/Classes/TagViewCell.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
1,030
```swift import Foundation // MARK: - UIPasteboard + Interlink // extension UIPasteboard { /// Copies the Internal Link (Markdown Reference) into the OS Pasteboard /// func copyInternalLink(to note: Note) { guard let link = note.markdownInternalLink else { return } string = link } /// Copies the Public Link (if any) into the OS Pasteboard /// func copyPublicLink(to note: Note) { guard let link = note.publicLink else { return } string = link } } ```
/content/code_sandbox/Simplenote/Classes/UIPasteboard+Note.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
126
```objective-c // // Tag.m // Simplenote // // Created by Michael Johnston on 10-04-19. // #import "Tag.h" //#import "NSArray+Utilities.h" #import "JSONKit+Simplenote.h" @interface Tag() - (void)updateRecipients; @end @implementation Tag @synthesize count; @dynamic index; @dynamic share; @dynamic name; - (void)awakeFromFetch { [super awakeFromFetch]; [self updateRecipients]; } - (id)initWithText:(NSString *)str { if ((self = [super init])) { self.name = str; self.recipients = [NSMutableArray arrayWithCapacity:2]; self.index = [NSNumber numberWithInt:-1]; } return self; } - (id)initWithText:(NSString *)str recipients:(NSArray *)emailList { if ((self = [super init])) { self.name = str; NSMutableArray *newEmailList = [emailList mutableCopy]; self.recipients = newEmailList; self.index = [NSNumber numberWithInt:-1]; } return self; } - (void)updateRecipients { if (share.length > 0) self.recipients = [share objectFromJSONString]; else self.recipients = [NSMutableArray arrayWithCapacity: 3]; } - (void)setRecipients:(NSMutableArray *)newRecipients { // Update share instead; recipients will get updated in setShare: below via updateRecipients self.share = [newRecipients count] > 0 ? [newRecipients JSONString] : @"[]"; } - (NSMutableArray *)recipients { return recipients; } - (NSComparisonResult)compareIndex:(Tag *)tag { int i1 = [[self index] intValue]; int i2 = [[tag index] intValue]; if (i1 >= 0 && i2 >= 0) { return [[self index] compare:[tag index]]; } else { return NSOrderedSame; } } -(NSString *)textWithPrefix { return [@"#" stringByAppendingString: name]; } -(void)addRecipient:(NSString *)emailAddress { NSString *newEmailAddress = [emailAddress copy]; [recipients addObject: newEmailAddress]; self.share = [recipients JSONString]; } -(NSDictionary *)tagDictionary { NSMutableDictionary *dict = [[NSMutableDictionary alloc] init]; [dict setObject:self.name forKey:@"name"]; if (self.recipients && [self.recipients count] > 0) [dict setObject:self.recipients forKey:@"share"]; [dict setObject:index forKey:@"index"]; return dict; } @end ```
/content/code_sandbox/Simplenote/Classes/Tag.m
objective-c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
543
```swift import Foundation import UIKit // MARK: - SPSortBar // class SPSortBar: UIView { /// Background Blur /// private let blurView = SPBlurEffectView.navigationBarBlurView() /// Divider: Top separator /// @IBOutlet private(set) var dividerView: UIView! /// Divider: We're aiming at a 1px divider, regardless of the screen scale /// @IBOutlet private var dividerHeightConstraint: NSLayoutConstraint! /// Container: Encapsulates every control! /// @IBOutlet private var containerView: UIView! /// Title: Sort By /// @IBOutlet private var titleLabel: UILabel! /// Description: Active Sort Mode /// @IBOutlet private var descriptionLabel: UILabel! /// Wraps up the Description Label Text /// var descriptionText: String? { get { descriptionLabel.text } set { descriptionLabel.text = newValue } } /// Closure to be executed whenever the Sort Mode Button is pressed /// var onSortModePress: (() -> Void)? // MARK: - Lifecycle deinit { stopListeningToNotifications() } override func awakeFromNib() { super.awakeFromNib() startListeningToNotifications() setupDividerView() setupBackgroundView() setupBlurEffect() setupTextLabels() setupSubviews() refreshStyle() } } // MARK: - Private Methods // private extension SPSortBar { func setupDividerView() { dividerHeightConstraint.constant = UIScreen.main.pointToPixelRatio } func setupBackgroundView() { containerView.backgroundColor = .clear } func setupBlurEffect() { blurView.tintColorClosure = { .simplenoteSortBarBackgroundColor } } func setupTextLabels() { titleLabel.text = NSLocalizedString("Sort by:", comment: "Sort By Title") titleLabel.font = .systemFont(ofSize: 12.0) descriptionLabel.font = .systemFont(ofSize: 12.0) } func setupSubviews() { insertSubview(blurView, at: .zero) blurView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ blurView.leadingAnchor.constraint(equalTo: leadingAnchor), blurView.trailingAnchor.constraint(equalTo: trailingAnchor), blurView.topAnchor.constraint(equalTo: topAnchor), blurView.bottomAnchor.constraint(equalTo: bottomAnchor) ]) } func refreshStyle() { dividerView.backgroundColor = .simplenoteDividerColor titleLabel.textColor = .simplenoteTextColor descriptionLabel.textColor = .simplenoteInteractiveTextColor } } // MARK: - Notifications // private extension SPSortBar { func startListeningToNotifications() { let nc = NotificationCenter.default nc.addObserver(self, selector: #selector(themeDidChange), name: .SPSimplenoteThemeChanged, object: nil) } func stopListeningToNotifications() { NotificationCenter.default.removeObserver(self) } @objc func themeDidChange() { refreshStyle() } } // MARK: - Action Handlers // private extension SPSortBar { @IBAction func sortModeWasPressed() { onSortModePress?() } } ```
/content/code_sandbox/Simplenote/Classes/SPSortBar.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
676
```objective-c #import "SPNavigationController.h" #import "Simplenote-Swift.h" static const NSInteger SPNavigationBarBackgroundPositionZ = -1000; @interface SPNavigationController () @property (nonatomic, strong) SPBlurEffectView *navigationBarBackground; @end @implementation SPNavigationController #pragma mark - Dynamic Properties - (void)viewDidLoad { [super viewDidLoad]; [self refreshBlurEffect]; } - (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; if (self.onWillDismiss) { self.onWillDismiss(); } } - (void)setDisplaysBlurEffect:(BOOL)displaysBlurEffect { if (_displaysBlurEffect == displaysBlurEffect) { return; } _displaysBlurEffect = displaysBlurEffect; if (self.isViewLoaded) { [self refreshBlurEffect]; } } - (void)setModalPresentationStyle:(UIModalPresentationStyle)modalPresentationStyle { [super setModalPresentationStyle:modalPresentationStyle]; [self refreshBlurTintColor]; } - (SPBlurEffectView *)navigationBarBackground { if (_navigationBarBackground) { return _navigationBarBackground; } SPBlurEffectView *navigationBarBackground = [SPBlurEffectView navigationBarBlurView]; navigationBarBackground.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; navigationBarBackground.layer.zPosition = SPNavigationBarBackgroundPositionZ; _navigationBarBackground = navigationBarBackground; return _navigationBarBackground; } #pragma mark - Blur Effect Support - (void)refreshBlurEffect { if (!self.displaysBlurEffect) { [self detachNavigationBarBackground]; return; } [self attachNavigationBarBackground:self.navigationBarBackground toNavigationBar:self.navigationBar]; } - (void)refreshBlurTintColor { // We'll use different Bar Tint Colors, based on the presentation style BOOL isModal = (self.modalPresentationStyle == UIModalPresentationFormSheet || self.modalPresentationStyle == UIModalPresentationPopover); self.navigationBarBackground.tintColorClosure = ^{ return isModal ? [UIColor simplenoteNavigationBarModalBackgroundColor] : [UIColor simplenoteNavigationBarBackgroundColor]; }; } - (void)detachNavigationBarBackground { [_navigationBarBackground removeFromSuperview]; } - (void)attachNavigationBarBackground:(UIVisualEffectView *)barBackground toNavigationBar:(UINavigationBar *)navigationBar { CGSize statusBarSize = [[UIApplication sharedApplication] keyWindowStatusBarHeight]; CGRect bounds = navigationBar.bounds; bounds.origin.y -= statusBarSize.height; bounds.size.height += statusBarSize.height; barBackground.frame = bounds; [navigationBar addSubview:barBackground]; [navigationBar sendSubviewToBack:barBackground]; } #pragma mark - Overridden Methods - (UIStatusBarStyle)preferredStatusBarStyle { return UIStatusBarStyleDefault; } - (BOOL)shouldAutorotate { return !_disableRotation; } @end ```
/content/code_sandbox/Simplenote/Classes/SPNavigationController.m
objective-c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
610
```swift import Foundation import SimplenoteSearch // MARK: - NotesListState // enum NotesListState: Equatable { case results case searching(query: SearchQuery) } // MARK: - NotesListState: Public API // extension NotesListState { /// Indicates if the NotesList should display Note Entities for the current state /// var displaysNotes: Bool { return true } /// Indicates if the NotesList should display Tag Entities for the current state /// var displaysTags: Bool { guard case .searching = self else { return false } return true } /// Returns the SectionIndex for Notes, in the current state /// var sectionIndexForNotes: Int { switch self { case .searching: return 1 default: return .zero } } /// Returns the SectionIndex for Tags, in the current state /// var sectionIndexForTags: Int { return .zero } /// Returns the SectionTitle for Notes, in the current state /// var sectionTitleForNotes: String? { switch self { case .searching: return NSLocalizedString("Notes", comment: "Notes Header (Search Mode)") default: return nil } } /// Returns the SectionTitle for Tags, in the current state /// var sectionTitleForTags: String? { switch self { case .searching: return NSLocalizedString("Search by Tag", comment: "Tags Header (Search Mode)") default: return nil } } /// Indicates if we should adjust SectionIndexes for ResultsController Changes entities /// var requiresNoteSectionIndexAdjustments: Bool { guard case .searching = self else { return false } return true } /// Returns a NSPredicate to filter out Notes in the current state, with the specified Filter /// func predicateForNotes(filter: NotesListFilter) -> NSPredicate? { var subpredicates = [NSPredicate]() switch self { case .results: subpredicates.append( NSPredicate.predicateForNotes(deleted: filter == .deleted) ) switch filter { case .tag(let name): subpredicates.append( NSPredicate.predicateForNotes(tag: name) ) case .untagged: subpredicates.append( NSPredicate.predicateForUntaggedNotes() ) default: break } case .searching(let query): subpredicates += [ NSPredicate.predicateForNotes(deleted: false), NSPredicate.predicateForNotes(query: query) ] } return NSCompoundPredicate(andPredicateWithSubpredicates: subpredicates) } /// Returns a NSPredicate to filter out Tags in the current state /// func predicateForTags() -> NSPredicate? { guard case let .searching(query) = self else { return nil } return NSPredicate.predicateForTags(in: query) } /// Returns a collection of NSSortDescriptors that, once applied to a Notes collection, the specified SortMode will be reflected /// func descriptorsForNotes(sortMode: SortMode) -> [NSSortDescriptor] { var descriptors = [NSSortDescriptor]() switch self { case .results: descriptors.append(NSSortDescriptor.descriptorForPinnedNotes()) default: // Search shouldn't be affected by pinned notes break } descriptors.append(NSSortDescriptor.descriptorForNotes(sortMode: sortMode)) return descriptors } /// Returns a collection of NSSortDescriptors that, once applied to a Tags collection, the specified SortMode will be reflected /// func descriptorsForTags() -> [NSSortDescriptor] { return [ NSSortDescriptor.descriptorForTags() ] } } ```
/content/code_sandbox/Simplenote/Classes/NotesListState.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
822
```swift import Foundation import UIKit // MARK: - SPRatingsPromptDelegate // @objc protocol SPRatingsPromptDelegate: AnyObject { func simplenoteWasLiked() func simplenoteWasDisliked() func displayReviewUI() func displayFeedbackUI() func dismissRatingsUI() } // MARK: - SPRatingsPromptView // class SPRatingsPromptView: UIView { /// Title /// @IBOutlet private var messageLabel: UILabel! /// Buttons Container /// @IBOutlet private var buttonsStackView: UIStackView! /// Leading Padding /// @IBOutlet private var leadingLayoutConstraint: NSLayoutConstraint! /// Trailing Padding /// @IBOutlet private var trailingLayoutConstraint: NSLayoutConstraint! /// Button: Left Action /// @IBOutlet private var leftButton: UIButton! /// Button: Right Action /// @IBOutlet private var rightButton: UIButton! /// Ratings State /// private var state = State.initial { didSet { refreshStrigs() } } /// Prompt's Delegate /// @objc weak var delegate: SPRatingsPromptDelegate? // MARK: - Lifecycle deinit { stopListeningToNotifications() } override func awakeFromNib() { super.awakeFromNib() startListeningToNotifications() refreshStyle() refreshStrigs() } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { refreshButtonsStackViewAxis() } } // MARK: - Private Methods // private extension SPRatingsPromptView { func refreshStyle() { refreshTitleStyle() refreshButtonsStyle() } func refreshTitleStyle() { messageLabel.font = .preferredFont(forTextStyle: .headline) messageLabel.textColor = .simplenoteNoteHeadlineColor } func refreshButtonsStyle() { let buttonColor = UIColor.simplenoteTintColor let buttonFont = UIFont.preferredFont(forTextStyle: .subheadline) let buttons = [leftButton, rightButton].compactMap { $0 } for button in buttons { button.backgroundColor = .clear button.layer.borderWidth = Settings.buttonBorderWidth button.layer.cornerRadius = Settings.buttonCornerRAdius button.layer.borderColor = buttonColor.cgColor button.titleLabel?.font = buttonFont button.setTitleColor(buttonColor, for: .normal) } } func refreshStrigs() { messageLabel.text = state.title leftButton.setTitle(state.leftTitle, for: .normal) rightButton.setTitle(state.rightTitle, for: .normal) } func refreshButtonsStackViewAxis() { guard let superviewWidth = superview?.frame.width else { return } buttonsStackView.axis = .horizontal let newButtonsWidth = buttonsStackView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).width let newFullWidth = leadingLayoutConstraint.constant + newButtonsWidth + trailingLayoutConstraint.constant if newFullWidth > superviewWidth { buttonsStackView.axis = .vertical } } } // MARK: - Notifications // private extension SPRatingsPromptView { func startListeningToNotifications() { let nc = NotificationCenter.default nc.addObserver(self, selector: #selector(themeDidChange), name: .SPSimplenoteThemeChanged, object: nil) } func stopListeningToNotifications() { NotificationCenter.default.removeObserver(self) } @objc func themeDidChange() { refreshStyle() setNeedsDisplay() } } // MARK: - Notifications // private extension SPRatingsPromptView { @IBAction func leftActionWasPressed() { switch state { case .initial: delegate?.simplenoteWasLiked() state = .liked case .liked: delegate?.displayReviewUI() case .disliked: delegate?.displayFeedbackUI() } } @IBAction func rightActionWasPressed() { switch state { case .initial: delegate?.simplenoteWasDisliked() state = .disliked case .liked, .disliked: delegate?.dismissRatingsUI() } } } // MARK: - Constants // private struct Settings { static let buttonBorderWidth = CGFloat(1) static let buttonCornerRAdius = CGFloat(4) } // MARK: - Ratings State // private enum State { case initial case liked case disliked } private extension State { var title: String { switch self { case .initial: return NSLocalizedString("What do you think about Simplenote?", comment: "Rating view initial title") case .liked: return NSLocalizedString("Great! Mind leaving a review to tell us what you like?", comment: "Rating view liked title") case .disliked: return NSLocalizedString("Could you tell us how we could improve?", comment: "Rating view disliked title") } } var leftTitle: String { switch self { case .initial: return NSLocalizedString("I like it", comment: "Rating view - initial - liked button") case .liked: return NSLocalizedString("Leave a review", comment: "Rating view - liked - leave review button") case .disliked: return NSLocalizedString("Send feedback", comment: "Rating view - disliked - send feedback button") } } var rightTitle: String { switch self { case .initial: return NSLocalizedString("Could be better", comment: "Rating view - initial - could be better button") case .liked, .disliked: return NSLocalizedString("No thanks", comment: "Rating view - liked or disliked - no thanks button") } } } ```
/content/code_sandbox/Simplenote/Classes/SPRatingsPromptView.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
1,212
```swift import Foundation // MARK: - NSMutableAttributedString Simplenote Methods // extension NSAttributedString { /// Returns the full range of the receiver. /// @objc var fullRange: NSRange { NSRange(location: .zero, length: length) } } ```
/content/code_sandbox/Simplenote/Classes/NSAttributedString+Simplenote.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
56
```swift import Foundation /// This extension contains several helper-additions to Cocoa NSURL class. /// extension NSURL { /// Returns *true* if the current URL is HTTP or HTTPS /// @objc func containsHttpScheme() -> Bool { return scheme == "http" || scheme == "https" } } ```
/content/code_sandbox/Simplenote/Classes/NSURL+Extensions.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
65
```swift import Foundation // MARK: - SPTextInputViewDelegate // @objc protocol SPTextInputViewDelegate: NSObjectProtocol { @objc optional func textInputDidBeginEditing(_ textInput: SPTextInputView) @objc optional func textInputDidEndEditing(_ textInput: SPTextInputView) @objc optional func textInputDidChange(_ textInput: SPTextInputView) @objc optional func textInputShouldReturn(_ textInput: SPTextInputView) -> Bool @objc optional func textInput(_ textInput: SPTextInputView, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool } // MARK: - SPTextInputView: // Renders a custom UITextView with bezel. When becomes the first responder, the border color will be refreshed. // @IBDesignable class SPTextInputView: UIView { /// Internal TextField /// private let textField = SPTextField() /// TextField's Autocapitalization Type /// @IBInspectable var autocapitalizationType: UITextAutocapitalizationType { get { return textField.autocapitalizationType } set { textField.autocapitalizationType = newValue } } /// TextField's Autocorrection Type /// @IBInspectable var autocorrectionType: UITextAutocorrectionType { get { return textField.autocorrectionType } set { textField.autocorrectionType = newValue } } /// Outer Border Color: Enabled State /// @IBInspectable var borderColorEnabled: UIColor? = .simplenoteGray20Color { didSet { refreshBorderStyle() } } /// Outer Border Color: Disabled State /// @IBInspectable var borderColorDisabled: UIColor? = .simplenoteGray5Color { didSet { refreshBorderStyle() } } /// Outer Border Color: Disabled State /// @IBInspectable var borderColorError: UIColor? = .simplenoteRed50Color { didSet { refreshBorderStyle() } } /// Outer Border Radius /// @IBInspectable var borderCornerRadius: CGFloat = Defaults.cornerRadius { didSet { refreshBorderStyle() } } /// Outer Border Width /// @IBInspectable var borderWidth: CGFloat = Defaults.borderWidth { didSet { refreshBorderStyle() } } /// Indicates if the input text should be obfuscated /// @IBInspectable var isSecureTextEntry: Bool { get { return textField.isSecureTextEntry } set { textField.isSecureTextEntry = newValue } } /// TextField's Keyboard Type /// @IBInspectable var keyboardType: UIKeyboardType { get { return textField.keyboardType } set { textField.keyboardType = newValue } } /// TextField's Placeholder Color /// @IBInspectable var placeholderColor: UIColor? { get { return textField.placeholdTextColor } set { textField.placeholdTextColor = newValue } } /// TextField's Return Key Type /// @IBInspectable var returnKeyType: UIReturnKeyType { get { return textField.returnKeyType } set { textField.returnKeyType = newValue } } /// TextField's Right View /// var rightView: UIView? { get { return textField.rightView } set { textField.rightView = newValue } } /// TextField's Right View Insets /// @IBInspectable var rightViewInsets: NSDirectionalEdgeInsets { get { return textField.rightViewInsets } set { textField.rightViewInsets = newValue } } /// TextField's Right View Visibility Mode /// @IBInspectable var rightViewMode: UITextField.ViewMode { get { return textField.rightViewMode } set { textField.rightViewMode = newValue } } /// TextField's Text /// @IBInspectable var text: String? { get { return textField.text } set { textField.text = newValue } } /// TextField's Text Color /// @IBInspectable var textColor: UIColor? { get { return textField.textColor } set { textField.textColor = newValue } } /// TextField Placeholder /// @IBInspectable var placeholder: String? { get { return textField.placeholder } set { textField.placeholder = newValue } } /// ContentType: Autofill Support! /// var textContentType: UITextContentType { get { textField.textContentType } set { textField.textContentType = newValue } } /// Password Rules /// var passwordRules: UITextInputPasswordRules? { get { textField.passwordRules } set { textField.passwordRules = newValue } } /// When toggled, the border color will be updated to borderColorError /// var inErrorState: Bool = false { didSet { refreshBorderStyle() } } /// Delegate Wrapper /// weak var delegate: SPTextInputViewDelegate? // MARK: - Initializers override init(frame: CGRect) { super.init(frame: frame) setupSubviews() setupWritingDirection() setupLayout() refreshBorderStyle() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupSubviews() setupWritingDirection() setupLayout() refreshBorderStyle() } // MARK: - Public Methods @discardableResult override func becomeFirstResponder() -> Bool { return textField.becomeFirstResponder() } } // MARK: - Private // private extension SPTextInputView { func setupSubviews() { textField.translatesAutoresizingMaskIntoConstraints = false textField.delegate = self textField.autocapitalizationType = .none textField.autocorrectionType = .no textField.placeholdTextColor = .simplenoteGray50Color textField.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged) addSubview(textField) } func setupWritingDirection() { // This should be `.natural`. However, the SDK isn't always a happy place: // iOS < 13.5: // *unless* you use a RTL-Keyboard, textAlignment will be .left // iOS = 13.5: // Works as expected // textField.textAlignment = userInterfaceLayoutDirection == .rightToLeft ? .right : .left } func setupLayout() { NSLayoutConstraint.activate([ textField.leadingAnchor.constraint(equalTo: leadingAnchor, constant: Defaults.insets.left), textField.trailingAnchor.constraint(equalTo: trailingAnchor, constant: Defaults.insets.right), textField.topAnchor.constraint(equalTo: topAnchor, constant: Defaults.insets.top), textField.bottomAnchor.constraint(equalTo: bottomAnchor, constant: Defaults.insets.bottom), ]) } func refreshBorderStyle() { let borderColor = inErrorState ? borderColorError : (textField.isFirstResponder ? borderColorEnabled : borderColorDisabled) layer.borderColor = borderColor?.cgColor layer.cornerRadius = borderCornerRadius layer.borderWidth = borderWidth } } // MARK: - Relaying editingChanged Events // extension SPTextInputView { @objc func textFieldDidChange(_ textField: UITextField) { delegate?.textInputDidChange?(self) } } // MARK: - UITextFieldDelegate // extension SPTextInputView: UITextFieldDelegate { func textFieldDidBeginEditing(_ textField: UITextField) { refreshBorderStyle() delegate?.textInputDidBeginEditing?(self) } func textFieldDidEndEditing(_ textField: UITextField) { delegate?.textInputDidBeginEditing?(self) refreshBorderStyle() } func textFieldShouldReturn(_ textField: UITextField) -> Bool { return delegate?.textInputShouldReturn?(self) ?? true } func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { return delegate?.textInput?(self, shouldChangeCharactersIn: range, replacementString: string) ?? true } } // MARK: - Default Settings // private enum Defaults { static let cornerRadius = CGFloat(4) static let borderWidth = CGFloat(1) static let insets = UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 0) } ```
/content/code_sandbox/Simplenote/Classes/SPTextInputView.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
1,807
```swift import Foundation import UIKit import SimplenoteInterlinks // MARK: - UITextView State // extension UITextView { /// Indicates if the receiver contains selected text /// @objc var isTextSelected: Bool { return selectedRange.length > 0 } /// Indicates if there's an ongoing Undo Operation in the Text Editor /// var isUndoingEditOP: Bool { undoManager?.isUndoing == true } } // MARK: - Updating! // extension UITextView { /// Inserts the specified Text at a given range. /// - Note: Resulting selected range will end up at the right hand side of the newly inserted text. /// func insertText(text: String, in range: Range<String.Index>) { registerUndoCheckpointAndPerform { storage in let range = NSRange(range, in: self.text) storage.replaceCharacters(in: range, with: text) let insertedTextRange = NSRange(text.fullRange, in: text) self.selectedRange = NSRange(location: range.location + insertedTextRange.length, length: .zero) } } } // MARK: - Undo Stack // private extension UITextView { /// Registers an Undo Checkpoint, and performs a given block `in a transactional fashion`: an Undo Group will wrap its execution /// /// 1. Registers an Undo Operation which is expected to restore the TextView to its previous state /// 2. Wraps up a given `Block` within an Undo Group /// 3. Post a TextDidChange Notification /// @discardableResult func registerUndoCheckpointAndPerform(block: (NSTextStorage) -> Void) -> Bool { guard let undoManager = undoManager else { return false } undoManager.beginUndoGrouping() registerUndoCheckpoint(in: undoManager, storage: textStorage) block(textStorage) undoManager.endUndoGrouping() notifyDidChangeText() return true } /// Registers an Undo Checkpoint, which is expected to restore the receiver to its previous state: /// /// 1. Restores the full contents of our TextStorage /// 2. Reverts the SelectedRange /// 3. Post a textDidChange Notification /// func registerUndoCheckpoint(in undoManager: UndoManager, storage: NSTextStorage) { let oldSelectedRange = selectedRange let oldText = storage.attributedSubstring(from: storage.fullRange) undoManager.registerUndo(withTarget: self) { textView in // Register an Undo *during* an Undo? > Also known as Redo! textView.registerUndoCheckpoint(in: undoManager, storage: storage) // And the actual Undo! storage.replaceCharacters(in: storage.fullRange, with: oldText) textView.selectedRange = oldSelectedRange textView.notifyDidChangeText() } } func notifyDidChangeText() { delegate?.textViewDidChange?(self) } } // MARK: - Interlinks // extension UITextView { /// Returns the Interlinking Keyword at the current Location (if any) /// var interlinkKeywordAtSelectedLocation: (Range<String.Index>, Range<String.Index>, String)? { guard let text = text, let range = Range(selectedRange, in: text) else { return nil } return text.interlinkKeyword(at: range.lowerBound) } } // MARK: - Attachments // extension UITextView { /// Returns the NSTextAttachment of the specified kind, ad a given Index. If possible /// func attachment<T: NSTextAttachment>(ofType: T.Type, at index: Int) -> T? { guard index < textStorage.length else { return nil } return attributedText.attribute(.attachment, at: index, effectiveRange: nil) as? T } } // MARK: - Geometry // extension UITextView { /// Returns the Bounding Rect for the specified `Range<String.Index>` /// func boundingRect(for range: Range<String.Index>) -> CGRect { let nsRange = NSRange(range, in: text) return boundingRect(for: nsRange) } /// Returns the Bounding Rect for the specified NSRange /// func boundingRect(for range: NSRange) -> CGRect { let glyphRange = layoutManager.glyphRange(forCharacterRange: range, actualCharacterRange: nil) let rect = layoutManager.boundingRect(forGlyphRange: glyphRange, in: textContainer) return rect.offsetBy(dx: textContainerInset.left, dy: textContainerInset.top) } /// Returns the "Editing Rect": We rely on this calculation to determine the "available area" in which Interlinks Autocomplete /// can be presented. /// /// - Note: `contentInset.bottom` is expected to contain the bottom padding required by the keyboard. Capisce? /// func editingRectInWindow() -> CGRect { let paddingTop = frame.minY + safeAreaInsets.top let paddingBottom = safeAreaInsets.bottom + contentInset.bottom let editingHeight = frame.height - paddingTop - paddingBottom let output = CGRect(x: frame.minX, y: paddingTop, width: frame.width, height: editingHeight) return superview?.convert(output, to: nil) ?? output } /// Returns the Window Location for the text at the specified range /// func locationInWindowForText(in range: Range<String.Index>) -> CGRect { let rectInEditor = boundingRect(for: range) return convert(rectInEditor, to: nil) } /// Returns the Selected Text's bounds /// @objc var selectedBounds: CGRect { guard selectedRange.length > 0 else { return .zero } let glyphRange = layoutManager.glyphRange(forCharacterRange: selectedRange, actualCharacterRange: nil) return layoutManager.boundingRect(forGlyphRange: glyphRange, in: textContainer) } } ```
/content/code_sandbox/Simplenote/Classes/UITextView+Simplenote.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
1,271
```swift import UIKit // MARK: RoundedCrossButton // class RoundedCrossButton: RoundedButton { /// Style /// enum Style { case standard case blue case tagPill } var style: Style = .standard { didSet { refreshStyle() } } override init(frame: CGRect) { super.init(frame: frame) configure() } required init?(coder: NSCoder) { super.init(coder: coder) configure() } deinit { stopListeningToNotifications() } } // MARK: - Private // private extension RoundedCrossButton { func configure() { startListeningToNotifications() refreshStyle() } func refreshStyle() { setImage(UIImage.image(name: .cross)?.withRenderingMode(.alwaysTemplate), for: .normal) switch style { case .standard: setBackgroundImage(UIColor.simplenoteCardDismissButtonBackgroundColor.dynamicImageRepresentation(), for: .normal) setBackgroundImage(UIColor.simplenoteCardDismissButtonHighlightedBackgroundColor.dynamicImageRepresentation(), for: .highlighted) tintColor = .simplenoteCardDismissButtonTintColor case .blue: setBackgroundImage(UIColor.simplenoteBlue30Color.dynamicImageRepresentation(), for: .normal) setBackgroundImage(UIColor.simplenoteBlue60Color.dynamicImageRepresentation(), for: .highlighted) tintColor = .white case .tagPill: setBackgroundImage(UIColor.simplenoteTagPillDeleteBackgroundColor.dynamicImageRepresentation(), for: .normal) tintColor = .simplenoteTagPillBackgroundColor } } } // MARK: - Notifications // private extension RoundedCrossButton { func startListeningToNotifications() { let nc = NotificationCenter.default nc.addObserver(self, selector: #selector(themeDidChange), name: .SPSimplenoteThemeChanged, object: nil) } func stopListeningToNotifications() { NotificationCenter.default.removeObserver(self) } @objc private func themeDidChange() { refreshStyle() } } ```
/content/code_sandbox/Simplenote/Classes/RoundedCrossButton.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
438
```swift import Foundation import UIKit // MARK: - SPBlurEffectView: Reacts automatically to UserInterfaceStyle Changes // @objc class SPBlurEffectView: UIVisualEffectView { /// Blur's TintView /// private let tintView: UIView = { let output = UIView() output.autoresizingMask = [.flexibleWidth, .flexibleHeight] return output }() /// Closure that's expected to return the TintColor we want. Runs on `iOS <13` everytime the active Theme is updated. /// @objc var tintColorClosure: (() -> UIColor)? { didSet { refreshTintColor() } } // MARK: - Initializers convenience init() { self.init(effect: .simplenoteBlurEffect) } convenience required init?(coder: NSCoder) { self.init(effect: .simplenoteBlurEffect) } init(effect: UIBlurEffect) { super.init(effect: effect) setupTintView() } } // MARK: - Private Methods // private extension SPBlurEffectView { func setupTintView() { contentView.addSubview(tintView) } @objc func refreshStyle() { refreshBlurEffect() refreshTintColor() } func refreshBlurEffect() { effect = UIBlurEffect.simplenoteBlurEffect } func refreshTintColor() { tintView.backgroundColor = tintColorClosure?() } } // MARK: - Static Methods // extension SPBlurEffectView { /// Adjust the receiver's alpha, to match a given ScrollView's ContentOffset /// @objc func adjustAlphaMatchingContentOffset(of scrollView: UIScrollView) { let maximumAlphaGradientOffset = CGFloat(22) let normalizedOffset = scrollView.adjustedContentInset.top + scrollView.contentOffset.y let newAlpha = min(max(normalizedOffset / maximumAlphaGradientOffset, 0), 1) guard alpha != newAlpha else { return } alpha = newAlpha } /// Returns a BlurEffectView meant to be used as a NavigationBar Background /// @objc static func navigationBarBlurView() -> SPBlurEffectView { let effectView = SPBlurEffectView() effectView.isUserInteractionEnabled = false effectView.tintColorClosure = { return .simplenoteNavigationBarBackgroundColor } return effectView } } ```
/content/code_sandbox/Simplenote/Classes/SPBlurEffectView.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
522
```swift import Foundation import UIKit // MARK: - SPSectionHeaderView // @objcMembers class SPSectionHeaderView: UITableViewHeaderFooterView { /// View Containing all of the subviews /// @IBOutlet private var containerView: UIView! /// Override `textLabel` to add `@IBOutlet` annotation /// @IBOutlet override var textLabel: UILabel? { get { return _textLabel } set { _textLabel = newValue } } private var _textLabel: UILabel? /// We're simply unable to build a TableVIewHeaderFooter, in IB, without triggering warnings about the contentView. /// SO: We're just loading a nib with the hieararchy we want, and manually attaching the top level container /// private lazy var nib = UINib(nibName: type(of: self).classNameWithoutNamespaces, bundle: nil) // MARK: - Overridden Methods override init(reuseIdentifier: String?) { super.init(reuseIdentifier: reuseIdentifier) configureSubviews() refreshStyle() } required init?(coder: NSCoder) { super.init(coder: coder) configureSubviews() refreshStyle() } override func prepareForReuse() { super.prepareForReuse() refreshStyle() } } // MARK: - Private Methods // private extension SPSectionHeaderView { /// Sets up the Subviews / Layout /// func configureSubviews() { nib.instantiate(withOwner: self, options: nil) contentView.addSubview(containerView) containerView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ containerView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor), containerView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor), containerView.topAnchor.constraint(equalTo: contentView.topAnchor), containerView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor) ]) } /// Refreshes the current Style current style /// func refreshStyle() { // Setting contentView.backgroundColor would be easier, but oh well, that triggers a console warning. let bgView = UIView() bgView.backgroundColor = .simplenoteTableViewHeaderBackgroundColor backgroundView = bgView textLabel?.textColor = .simplenoteTextColor textLabel?.font = UIFont.preferredFont(for: .body, weight: .semibold) } } ```
/content/code_sandbox/Simplenote/Classes/SPSectionHeaderView.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
483
```objective-c // // NSString+Bullets.h // Simplenote // // Created by Tom Witkin on 8/25/13. // #import <Foundation/Foundation.h> @interface NSString (Bullets) + (NSString *)spaceString; + (NSString *)tabString; + (NSString *)newLineString; - (BOOL)isNewlineString; - (BOOL)isTabString; @end ```
/content/code_sandbox/Simplenote/Classes/NSString+Bullets.h
objective-c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
84
```objective-c // // SPTextView.m // Simplenote // // Created by Tom Witkin on 7/19/13. // Created by Michael Johnston on 7/19/13. // #import "SPTextView.h" #import <CoreFoundation/CFStringTokenizer.h> #import "SPInteractiveTextStorage.h" #import "Simplenote-Swift.h" CGFloat const TextViewHighlightHorizontalPadding = 3; CGFloat const TextViewHighlightCornerRadius = 3; @implementation SPTextView - (instancetype)init { SPInteractiveTextStorage *textStorage = [[SPInteractiveTextStorage alloc] init]; NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init]; NSTextContainer *container = [[NSTextContainer alloc] initWithSize:CGSizeMake(0, CGFLOAT_MAX)]; container.widthTracksTextView = YES; container.heightTracksTextView = YES; [layoutManager addTextContainer:container]; [textStorage addLayoutManager:layoutManager]; self = [super initWithFrame:CGRectZero textContainer:container]; if (self) { self.interactiveTextStorage = textStorage; /* Issue #188: =========== On iOS 8, the text (was) getting clipped onscreen. Reason: the TextContainer was being shrunk down, and never re-expanded. This was not happening on iOS 7, because [UITextView setScrollEnabled] method was disabling the textContainer.heightTracksTextView property (and thus, the NSTextContainer instance was maintaining the CGFLOAT_MAX height. As a workaround, we're disabling heightTracksTextView here, emulating iOS 7 behavior. NOTE: Disabling heightTracksTextView before the init has a side effect. caretRectForPosition will not calculate the right caret position. */ self.textContainer.heightTracksTextView = NO; } return self; } #pragma mark - Words - (void)highlightRange:(NSRange)range animated:(BOOL)animated withBlock:(void (^)(CGRect))block { [self clearHighlights:animated]; highlightViews = [NSMutableArray arrayWithCapacity:range.length]; [self.layoutManager enumerateLineFragmentsForGlyphRange:range usingBlock:^(CGRect rect, CGRect usedRect, NSTextContainer *textContainer, NSRange glyphRange, BOOL *stop) { NSInteger location = MAX(glyphRange.location, range.location); NSInteger length = MIN(glyphRange.length, range.length - (location - range.location)); NSRange highlightRange = NSMakeRange(location, length); CGRect highlightRect = [self.layoutManager boundingRectForGlyphRange:highlightRange inTextContainer:textContainer]; highlightRect.origin.y += self.textContainerInset.top; if (block) block(highlightRect); UIView *highlightView = [self createHighlightViewForAttributedString:[self.textStorage attributedSubstringFromRange:highlightRange] frame:highlightRect]; [self addSubview:highlightView]; [self->highlightViews addObject:highlightView]; if (animated) { [UIView animateWithDuration:0.1 animations:^{ highlightView.transform = CGAffineTransformMakeScale(1.2, 1.2); } completion:^(BOOL finished) { [UIView animateWithDuration:0.1 delay:0.0 usingSpringWithDamping:0.6 initialSpringVelocity:10.0 options:UIViewAnimationOptionCurveEaseOut animations:^{ highlightView.transform = CGAffineTransformIdentity; } completion:nil]; }]; } }]; } - (UIView *)createHighlightViewForAttributedString:(NSAttributedString *)attributedString frame:(CGRect)frame { frame.size.width += 2 * TextViewHighlightHorizontalPadding; frame.origin.x -= TextViewHighlightHorizontalPadding; UILabel *highlightLabel = [[UILabel alloc] initWithFrame:frame]; NSMutableAttributedString *mutableAttributedString = [[NSMutableAttributedString alloc] initWithAttributedString:attributedString]; [mutableAttributedString addAttributes:@{ NSForegroundColorAttributeName: [UIColor simplenoteEditorSearchHighlightTextColor], NSBackgroundColorAttributeName: [UIColor simplenoteEditorSearchHighlightSelectedColor] } range:NSMakeRange(0, mutableAttributedString.length)]; highlightLabel.attributedText = mutableAttributedString; highlightLabel.textAlignment = NSTextAlignmentCenter; highlightLabel.backgroundColor = [UIColor simplenoteEditorSearchHighlightSelectedColor]; highlightLabel.layer.cornerRadius = TextViewHighlightCornerRadius; highlightLabel.clipsToBounds = YES; highlightLabel.layer.shouldRasterize = YES; highlightLabel.layer.rasterizationScale = [[UIScreen mainScreen] scale]; return highlightLabel; } - (void)clearHighlights:(BOOL)animated { if (animated) { for (UIView *highlightView in highlightViews) { UIView *highlightSnapshot = [highlightView snapshotViewAfterScreenUpdates:NO]; highlightSnapshot.frame = highlightView.frame; [self addSubview:highlightSnapshot]; [UIView animateWithDuration:0.1 animations:^{ highlightSnapshot.alpha = 0.0; highlightSnapshot.transform = CGAffineTransformMakeScale(0.0, 0.0); } completion:^(BOOL finished) { [highlightSnapshot removeFromSuperview]; }]; } } for (UIView *highlightView in highlightViews) { [highlightView removeFromSuperview]; } highlightViews = nil; } - (void)clearHighlights { [self clearHighlights:NO]; } #pragma mark - - (void)scrollRectToVisible:(CGRect)rect animated:(BOOL)animated { // This is a work around for an issue where the text view scrolls to its bottom // when a user selects all text. If the selected range matches the range of the // string, this method was likely called as a result of choosing the "Select All" method // of a UIMenuItem. In these cases we just return to avoid scrolling the view. // For more info, see: path_to_url NSRange range = [self.text rangeOfString:self.text]; NSRange selectedRange = self.selectedRange; if (range.location == selectedRange.location && range.length == selectedRange.length) { return; } [super scrollRectToVisible:rect animated:animated]; } - (void)setContentOffset:(CGPoint)contentOffset animated:(BOOL)animated { if (!self.enableScrollSmoothening || !animated) { [super setContentOffset:contentOffset animated:animated]; return; } /// Secret Technique /// In order to _extremely_ match "Scroll to Selected Range" with any Keyboard animation, we'll introduce a custom animation. /// This yields a smooth experience, whenever the keyboard is revealed (and the TextView decides to scroll along) const UIViewAnimationOptions options = UIViewAnimationOptionAllowUserInteraction | UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionLayoutSubviews; const NSTimeInterval duration = 0.25; [UIViewPropertyAnimator runningPropertyAnimatorWithDuration:duration delay:UIKitConstants.animationDelayZero options:options animations:^{ [self setContentOffset:contentOffset]; } completion:nil]; } @end ```
/content/code_sandbox/Simplenote/Classes/SPTextView.m
objective-c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
1,517
```swift import Foundation import UIKit // MARK: - UISearchBar Simplenote Methods // extension UISearchBar { /// Applies Simplenote's Style /// @objc func applySimplenoteStyle() { backgroundColor = .clear setBackgroundImage(UIImage(), for: .any, barMetrics: .default) setSearchFieldBackgroundImage(.searchBarBackgroundImage, for: .normal) // Apply font to search field by traversing subviews for textField in subviewsOfType(UITextField.self) { textField.textColor = .simplenoteTextColor textField.keyboardAppearance = SPUserInterface.isDark ? .dark : .default } } @objc func refreshPlaceholderStyle(searchEnabled enabled: Bool = true) { for textField in subviewsOfType(UITextField.self) { if let text = textField.placeholder { let color: UIColor = enabled ? .simplenotePlaceholderTextColor : .simplenoteDisabledPlaceholderTextColor let attributes = [NSAttributedString.Key.foregroundColor: color] let attributedText = NSAttributedString(string: text, attributes: attributes) textField.attributedPlaceholder = attributedText } } } } ```
/content/code_sandbox/Simplenote/Classes/UISearchBar+Simplenote.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
250
```swift import Foundation // MARK: - KeychainManager // enum KeychainManager { /// Simplenote's Share Extension Token /// @KeychainItemWrapper(service: SimplenoteKeychain.extensionService, account: SimplenoteKeychain.extensionAccount) static var extensionToken: String? /// Simplenote's PIN Lock Keychain Item /// @KeychainItemWrapper(service: SimplenoteKeychain.pinlockService, account: SimplenoteKeychain.pinlockAccount) static var pinlock: String? /// Simplenote's Timestamp Keychain Item /// @KeychainItemWrapper(service: SimplenoteKeychain.timestampService, account: SimplenoteKeychain.timestampAccount) static var timestamp: String? } // MARK: - KeychainItemWrapper // @propertyWrapper struct KeychainItemWrapper { let item: KeychainPasswordItem /// Designated Initializer /// init(service: String, account: String) { item = KeychainPasswordItem(service: service, account: account) } var wrappedValue: String? { mutating get { do { return try item.readPassword() } catch KeychainError.noPassword { return nil } catch { NSLog("Error Reading Keychain Item \(item.service).\(item.account): \(error)") return nil } } set { do { if let value = newValue { try item.savePassword(value) } else { try item.deleteItem() } } catch { NSLog("Error Setting Keychain Item \(item.service).\(item.account)") } } } } // MARK: - Keychain Constants // enum SimplenoteKeychain { /// Extension Token /// static let extensionAccount = "Main" static let extensionService = "SimplenoteShare" /// Pinlock /// static let pinlockAccount = "SimplenotePin" static let pinlockService = pinlockAccount /// Timestamp /// static let timestampAccount = "Main" static let timestampService = "simplenote-passcode" } ```
/content/code_sandbox/Simplenote/Classes/KeychainManager.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
458
```swift import Foundation import UIKit // MARK: - UIAlertController's Simplenote Methods // extension UIViewController { /// View to use to attach another view controller /// enum AttachmentView { case below(UIView) case into(UIView) } /// Presents the receiver from the RootViewController's leaf /// @objc func presentFromRootViewController() { // Note: // This method is required because the presenter ViewController must be visible, and we've got several // flows in which the VC that triggers the alert, might not be visible anymore. // guard let rootViewController = UIApplication.shared.delegate?.window??.rootViewController else { print("Error loading the rootViewController") return } var leafViewController = rootViewController while leafViewController.presentedViewController != nil { leafViewController = leafViewController.presentedViewController! } leafViewController.present(self, animated: true, completion: nil) } /// Attaches a children ViewController (if needed) below the specified sibling view /// func attach(to parent: UIViewController, attachmentView: AttachmentView? = nil, animated: Bool = false) { guard self.parent != parent else { return } detach() parent.addChild(self) let attachmentView = attachmentView ?? .into(parent.view) switch attachmentView { case .below(let siblingView): siblingView.superview?.insertSubview(view, belowSubview: siblingView) siblingView.superview?.pinSubviewToAllEdges(view) case .into(let containerView): containerView.addFillingSubview(view) } let taskBlock = { self.didMove(toParent: parent) } if animated { view.fadeIn { _ in taskBlock() } } else { taskBlock() } } /// Detaches the receiver from its parent /// func detach(animated: Bool = false) { guard parent != nil else { return } let taskBlock = { self.view.removeFromSuperview() self.removeFromParent() } willMove(toParent: nil) if animated { view.fadeOut { _ in taskBlock() } } else { taskBlock() } } } ```
/content/code_sandbox/Simplenote/Classes/UIViewController+Simplenote.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
476
```objective-c #import "SPModalActivityIndicator.h" #import "Simplenote-Swift.h" @implementation SPModalActivityIndicator + (SPModalActivityIndicator *)showInWindow:(UIWindow *)window { SPModalActivityIndicator *alertView = [[SPModalActivityIndicator alloc] initWithFrame:CGRectZero]; UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleMedium]; [activityIndicator startAnimating]; [alertView showWithContentView:activityIndicator window:window]; return alertView; } - (void)showWithContentView:(UIView *)cView window:(UIWindow *)window { self.contentView = cView; topView = window; self.contentView.clipsToBounds = YES; [self applyStyling]; [self setupLayout]; self.alpha = 0.2; self.contentView.transform = CGAffineTransformMakeScale(4.0, 4.0); [UIView animateWithDuration:0.6 delay:0.0 usingSpringWithDamping:0.7 initialSpringVelocity:0.5 options:UIViewAnimationOptionCurveEaseOut animations:^{ self.alpha = 1.0; self.contentView.transform = CGAffineTransformIdentity; } completion:nil]; } - (void)applyStyling { self.backgroundColor = [UIColor simplenoteModalOverlayColor]; } -(void)setupLayout { CGRect topViewBounds = topView.bounds; float contentHeight = _contentView.frame.size.height; float contentWidth = _contentView.frame.size.width; float boxHeight = contentHeight; float boxWidth = contentWidth; float xOrigin = (topView.bounds.size.width - boxWidth) / 2; float yOrigin = (topView.bounds.size.height - boxWidth) / 2; boxFrame = CGRectMake(xOrigin, yOrigin, boxWidth, boxHeight); CGRect contentFrame = CGRectMake(boxFrame.origin.x, boxFrame.origin.y, contentWidth, contentHeight); self.contentView.frame = contentFrame; self.frame = topViewBounds; [self setNeedsDisplay]; [self addSubview:self.contentView]; [topView addSubview:self]; self.userInteractionEnabled = YES; } - (void)dismiss:(BOOL)animated completion:(void (^)())completion { if (!animated) [self dismissComplete]; else { [UIView animateWithDuration:0.1 animations:^{ self.transform = CGAffineTransformMakeScale(1.1, 1.1); } completion:^(BOOL finished) { [UIView animateWithDuration:1.0 delay:0.0 usingSpringWithDamping:0.7 initialSpringVelocity:0.5 options:UIViewAnimationOptionCurveEaseOut animations:^{ self.alpha = 0.0; self.contentView.transform = CGAffineTransformMakeScale(0.5, 0.5); } completion:^(BOOL finished) { [self dismissComplete]; }]; }]; } } - (void)dismissComplete { [self removeFromSuperview]; } @end ```
/content/code_sandbox/Simplenote/Classes/SPModalActivityIndicator.m
objective-c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
661
```objective-c @interface NSProcessInfo (Util) + (BOOL)isRunningTests; @end ```
/content/code_sandbox/Simplenote/Classes/NSProcessInfo+Util.h
objective-c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
19
```objective-c // // SPNotifications.h // Simplenote // // #import <Foundation/Foundation.h> #pragma mark ================================================================================ #pragma mark Notifications #pragma mark ================================================================================ extern NSString *const SPAlphabeticalTagSortPreferenceChangedNotification; extern NSString *const SPCondensedNoteListPreferenceChangedNotification; extern NSString *const SPNotesListSortModeChangedNotification; extern NSString *const SPSimplenoteThemeChangedNotification; extern NSString *const SPSubscriptionStatusDidChangeNotification; ```
/content/code_sandbox/Simplenote/Classes/SPNotifications.h
objective-c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
97
```swift import Foundation // MARK: - NoteContentHelper // enum NoteContentHelper { /// Returns structure of the content: range of title and body /// /// - Parameters: /// - content: note content /// static func structure(of content: String?) -> (title: Range<String.Index>?, body: Range<String.Index>?, trimmedBody: Range<String.Index>?) { guard let content = content, !content.isEmpty else { return (title: nil, body: nil, trimmedBody: nil) } guard let titleRange = trimmedTextRange(in: content, startingFrom: content.startIndex, endAtNewline: true) else { return (title: nil, body: nil, trimmedBody: nil) } guard let bodyStartLocation = content.rangeOfFirstCharacter(from: .newlines, startingFrom: titleRange.upperBound)?.upperBound else { return (title: titleRange, body: nil, trimmedBody: nil) } let bodyRange = bodyStartLocation..<content.endIndex let trimmedBodyRange = trimmedTextRange(in: content, startingFrom: bodyStartLocation, endAtNewline: false) return (title: titleRange, body: bodyRange, trimmedBody: trimmedBodyRange) } private static func trimmedTextRange(in content: String, startingFrom startLocation: String.Index, endAtNewline: Bool) -> Range<String.Index>? { guard let firstCharacterLocation = content.locationOfFirstCharacter(from: CharacterSet.whitespacesAndNewlines.inverted, startingFrom: startLocation) else { return nil } let endRangeLocation: String.Index = { if !endAtNewline { return content.endIndex } // Look for the next newline let newlineLocation = content.locationOfFirstCharacter(from: CharacterSet.newlines, startingFrom: firstCharacterLocation) return newlineLocation ?? content.endIndex }() guard let lastCharacterLocation = content.locationOfFirstCharacter(from: CharacterSet.whitespacesAndNewlines.inverted, startingFrom: endRangeLocation, backwards: true) else { return nil } return firstCharacterLocation..<content.index(after: lastCharacterLocation) } } ```
/content/code_sandbox/Simplenote/Classes/NoteContentHelper.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
479
```objective-c // // Note.h // Simplenote // // Created by Michael Johnston on 01/07/08. // #import <Simperium/SPManagedObject.h> @interface Note : SPManagedObject { NSString *content; NSString *modificationDatePreview; NSString *creationDatePreview; NSString *titlePreview; NSString *contentPreview; NSString *shareURL; NSString *publishURL; NSDate *creationDate; NSDate *modificationDate; NSString *tags; NSString *systemTags; NSMutableArray *tagsArray; NSMutableArray *systemTagsArray; NSString *remoteId; int lastPosition; BOOL pinned; BOOL markdown; BOOL deleted; BOOL shared; BOOL published; BOOL unread; NSDictionary *versions; } @property (nonatomic, copy) NSString *content; @property (nonatomic, copy) NSString *publishURL; @property (nonatomic, copy) NSDate *modificationDate; @property (nonatomic, copy) NSString *tags; @property (nonatomic, strong) NSMutableArray<NSString*> *tagsArray; @property (nonatomic, copy) NSString *shareURL; @property (nonatomic, copy) NSDate *creationDate; @property (nonatomic, copy) NSString *systemTags; @property (nonatomic, copy) NSString *modificationDatePreview; @property (nonatomic, copy) NSString *creationDatePreview; @property (nonatomic, copy) NSString *titlePreview; @property (nonatomic, copy) NSString *bodyPreview; // What's going on: // // - Since Simplenote's inception, logic deletion flag was a simple boolean called `deleted` // - Collision with NSManagedObject's `deleted` flag wasn't picked up // - Eventually CLANG enhanced checks allowed us to notice there's a collision // // Proper fix involves a heavy modification in Simperium, which would allow us to keep the `deleted` "internal" // property name, while exposing a different property setter / getter, and thus, avoiding the collision. // // In This thermonuclear massive super workaround, we're simply silencing the warning. // // Proper course of action should be taken as soon as the next steps for Simperium are outlined. // // TODO: JLP Dec.3.2019. // #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wproperty-attribute-mismatch" @property BOOL deleted; #pragma clang diagnostic pop @property (nonatomic, assign) int lastPosition; @property (nonatomic, assign) BOOL pinned; @property (nonatomic, assign) BOOL markdown; @property (nonatomic, assign) BOOL shared; @property (nonatomic, assign) BOOL published; @property (nonatomic, assign) BOOL unread; - (NSString *)dateString:(NSDate *)date brief:(BOOL)brief; - (NSString *)creationDateString:(BOOL)brief; - (NSString *)modificationDateString:(BOOL)brief; - (NSString *)localID; - (void)updateTagsArray; - (void)updateSystemTagsArray; - (BOOL)hasTags; - (BOOL)hasTag:(NSString *)tag; - (void)addTag:(NSString *)tag; - (void)addSystemTag:(NSString *)tag; - (void)setSystemTagsFromList:(NSArray *)tagList; - (void)stripSystemTag:(NSString *)tag; - (BOOL)hasSystemTag:(NSString *)tag; - (void)setTagsFromList:(NSArray *)tagList; - (void)stripTag:(NSString *)tag; - (void)ensurePreviewStringsAreAvailable; - (NSDictionary *)noteDictionaryWithContent:(BOOL)include; - (BOOL)isList; @end ```
/content/code_sandbox/Simplenote/Classes/Note.h
objective-c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
796
```objective-c #import "SPSidebarContainerViewController.h" #import "SPTracker.h" #import "Simplenote-Swift.h" #import <UIKit/UIKit.h> static const CGFloat SPDirectionalIdentity = 1; static const CGFloat SPDirectionalInverted = -1; static const CGFloat SPSidebarWidth = 300; static const CGFloat SPSidebarAnimationThreshold = 0.15; static const CGFloat SPSidebarAnimationDuration = 0.35; static const CGFloat SPSidebarAnimationDamping = 10; static const CGVector SPSidebarAnimationInitialVelocity = {-10, 0}; static const CGFloat SPSidebarAnimationCompletionMin = 0.001; static const CGFloat SPSidebarAnimationCompletionMax = 0.999; static const CGFloat SPSidebarAnimationCompletionFactorFull = 1.0; static const CGFloat SPSidebarAnimationCompletionFactorZero = 0.0; @interface SPSidebarContainerViewController () <UIGestureRecognizerDelegate> @property (nonatomic, strong) UIViewController *sidebarViewController; @property (nonatomic, strong) UIViewController *mainViewController; @property (nonatomic, strong) UIViewPropertyAnimator *animator; @property (nonatomic, strong) UITapGestureRecognizer *mainViewTapGestureRecognier; @property (nonatomic, strong) UIPanGestureRecognizer *panGestureRecognizer; @property (nonatomic, assign) BOOL isSidebarVisible; @property (nonatomic, assign) BOOL isPanningActive; @end @implementation SPSidebarContainerViewController - (instancetype)initWithMainViewController:(UIViewController *)mainViewController sidebarViewController:(UIViewController *)sidebarViewController { NSParameterAssert(mainViewController); NSParameterAssert(sidebarViewController); self = [super init]; if (self) { self.mainViewController = mainViewController; self.sidebarViewController = sidebarViewController; self.automaticallyMatchSidebarInsetsWithMainInsets = YES; [self configurePanGestureRecognizer]; [self configureTapGestureRecognizer]; [self configureViewControllerContainment]; } return self; } - (void)viewDidLoad { [super viewDidLoad]; [self configureView]; [self attachMainView]; [self attachSidebarView]; [self startListeningToNotifications]; } - (BOOL)shouldAutomaticallyForwardAppearanceMethods { // We're officially taking over the Appearance Methods sequence, for Child ViewControllers return NO; } - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; [self.mainViewController beginAppearanceTransition:YES animated:animated]; } - (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; [self.mainViewController endAppearanceTransition]; } - (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; [self.mainViewController beginAppearanceTransition:NO animated:animated]; } - (void)viewDidDisappear:(BOOL)animated { [super viewDidDisappear:animated]; [self.mainViewController endAppearanceTransition]; } - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator { [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator]; [coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> _Nonnull context) { [self ensureSideTableViewInsetsMatchMainViewInsets]; } completion:nil]; } #pragma mark - Dynamic Properties - (UIView *)mainView { return self.mainViewController.view; } - (UIView *)sidebarView { return self.sidebarViewController.view; } - (UIView *)mainChildView { // We assume that the MainViewController might actually be a UINavigationController, and we'll return the Top View return self.mainNavigationController.viewControllers.firstObject.view ?: self.mainView; } - (UITableView *)mainChildTableView { return [self.mainChildView firstSubviewAsTableView]; } - (UITableView *)sideChildTableView { return [self.sidebarView firstSubviewAsTableView]; } - (UIViewController *)activeViewController { return self.isSidebarVisible ? self.sidebarViewController : self.mainViewController; } - (UINavigationController *)mainNavigationController { if (![self.mainViewController isKindOfClass:UINavigationController.class]) { return nil; } return (UINavigationController *)self.mainViewController; } #pragma mark - Overridden Methods - (UIStatusBarStyle)preferredStatusBarStyle { return UIStatusBarStyleDefault; } - (BOOL)shouldAutorotate { return !self.isPanningActive && [self.activeViewController shouldAutorotate]; } #pragma mark - Initialization - (void)configureView { NSParameterAssert(self.panGestureRecognizer); self.view.backgroundColor = [UIColor simplenoteBackgroundColor]; [self.view addGestureRecognizer:self.panGestureRecognizer]; } - (void)configurePanGestureRecognizer { self.panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGestureWasRecognized:)]; self.panGestureRecognizer.delegate = self; } - (void)configureTapGestureRecognizer { self.mainViewTapGestureRecognier = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(rootViewTapped:)]; self.mainViewTapGestureRecognier.numberOfTapsRequired = 1; self.mainViewTapGestureRecognier.numberOfTouchesRequired = 1; } - (void)configureViewControllerContainment { NSParameterAssert(self.mainViewController); NSParameterAssert(self.sidebarViewController); [self.mainViewController willMoveToParentViewController:self]; [self.sidebarViewController willMoveToParentViewController:self]; [self addChildViewController:self.mainViewController]; [self addChildViewController:self.sidebarViewController]; [self.mainViewController didMoveToParentViewController:self]; [self.sidebarViewController didMoveToParentViewController:self]; } - (void)attachMainView { NSParameterAssert(self.mainView); [self.view addSubview:self.mainView]; } - (void)attachSidebarView { NSParameterAssert(self.sidebarView); CGRect sidePanelFrame = self.view.bounds; sidePanelFrame.origin.x = self.isRightToLeft ? sidePanelFrame.size.width : -SPSidebarWidth; sidePanelFrame.size.width = SPSidebarWidth; UIView *sidebarView = self.sidebarView; sidebarView.frame = sidePanelFrame; sidebarView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleRightMargin; [self.view insertSubview:sidebarView atIndex:0]; } - (void)encodeRestorableStateWithCoder:(NSCoder *)coder { [super encodeRestorableStateWithCoder:coder]; [coder encodeObject:self.mainViewController forKey:@"MainControllerEncodeKey"]; [coder encodeObject:self.sidebarViewController forKey:@"SideControllerEncodeKey"]; } #pragma mark - Notifications - (void)startListeningToNotifications { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshStyle) name:SPSimplenoteThemeChangedNotification object:nil]; } - (void)refreshStyle { self.view.backgroundColor = [UIColor simplenoteBackgroundColor]; } #pragma mark - Gestures - (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)recognizer { if (recognizer != self.panGestureRecognizer) { return YES; } CGPoint translation = [self.panGestureRecognizer translationInView:self.panGestureRecognizer.view]; // Scenario A: It's a Vertical Swipe if (ABS(translation.x) < ABS(translation.y)) { return NO; } // Scenario B: Sidebar is NOT visible, and we got a Left Swipe (OR) Sidebar is Visible and we got a Right Swipe CGFloat normalizedTranslation = translation.x * self.directionalMultiplier; if ((!self.isSidebarVisible && normalizedTranslation < 0) || (self.isSidebarVisible && normalizedTranslation > 0)) { return NO; } // Scenario C: Sidebar or Main are being dragged if (self.mainChildTableView.dragging || self.sideChildTableView.dragging) { return NO; } // Scenario D: Sidebar is not visible, but there are multiple viewControllers in its hierarchy if (!self.isSidebarVisible && self.mainNavigationController.viewControllers.count > 1) { return NO; } // Scenario E: Sidebar is not visible, but the delegate says NO, NO! if (!self.isSidebarVisible && ![self.delegate sidebarContainerShouldDisplaySidebar:self]) { return NO; } // Scenario F: Sidebar is visible and is being edited if (self.isSidebarVisible && self.sidebarViewController.isEditing) { return NO; } // Scenario G: We're still tracking something? if (self.isPanningActive) { return NO; } return YES; } - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer { // Why is this needed: UITableView's swipe gestures might require our Pan gesture to fail. Capisci? if (gestureRecognizer != self.panGestureRecognizer) { return YES; } // In the name of your king, stop this madness! return !self.isPanningActive; } #pragma mark - Helpers // The following method will (attempt) to match the Sidebar's TableViewInsets with the MainView's SafeAreaInsets. // Ideally, the first Sidebar row will be aligned against the SearchBar on its right hand side. // - (void)ensureSideTableViewInsetsMatchMainViewInsets { UIEdgeInsets mainSafeInsets = self.mainChildView.safeAreaInsets; UITableView* sideTableView = self.sideChildTableView; if (!self.automaticallyMatchSidebarInsetsWithMainInsets || sideTableView == nil) { return; } UIEdgeInsets contentInsets = sideTableView.contentInset; UIEdgeInsets scrollIndicatorInsets = sideTableView.verticalScrollIndicatorInsets; contentInsets.top = mainSafeInsets.top; contentInsets.bottom = mainSafeInsets.bottom; // Yes. Not setting the bottomInsets on purpose. scrollIndicatorInsets.top = mainSafeInsets.top; if (UIEdgeInsetsEqualToEdgeInsets(sideTableView.contentInset, contentInsets)) { return; } sideTableView.contentInset = contentInsets; sideTableView.scrollIndicatorInsets = scrollIndicatorInsets; [sideTableView scrollToTopWithAnimation:NO]; } #pragma mark - UIViewPropertyAnimator - (UIViewPropertyAnimator *)animatorForSidebarVisibility:(BOOL)visible { CGAffineTransform transform = visible ? CGAffineTransformMakeTranslation(SPSidebarWidth * self.directionalMultiplier, 0) : CGAffineTransformIdentity; CGFloat alphaSidebar = visible ? UIKitConstants.alpha1_0 : UIKitConstants.alpha0_0; CGFloat alphaMain = visible ? UIKitConstants.alpha0_5 : UIKitConstants.alpha1_0; UISpringTimingParameters *parameters = [[UISpringTimingParameters alloc] initWithDampingRatio:SPSidebarAnimationDamping initialVelocity:SPSidebarAnimationInitialVelocity]; UIViewPropertyAnimator *animator = [[UIViewPropertyAnimator alloc] initWithDuration:SPSidebarAnimationDuration timingParameters:parameters]; [animator addAnimations:^{ self.mainView.transform = transform; self.mainView.alpha = alphaMain; self.sidebarView.transform = transform; self.sidebarView.alpha = alphaSidebar; }]; return animator; } #pragma mark - UIGestureRecognizers - (void)panGestureWasRecognized:(UIPanGestureRecognizer *)gesture { if (gesture.state == UIGestureRecognizerStateBegan) { BOOL newVisibility = !self.isSidebarVisible; self.animator = [self animatorForSidebarVisibility:newVisibility]; self.isPanningActive = YES; [self beginSidebarTransition:newVisibility]; [SPTracker trackSidebarSidebarPanned]; } else if (gesture.state == UIGestureRecognizerStateEnded || gesture.state == UIGestureRecognizerStateCancelled || gesture.state == UIGestureRecognizerStateFailed) { if (self.animator.fractionComplete < SPSidebarAnimationThreshold) { self.animator.reversed = YES; [self beginSidebarTransition:self.isSidebarVisible]; } else { self.isSidebarVisible = !self.isSidebarVisible; } __weak typeof(self) weakSelf = self; BOOL didBecomeVisible = self.isSidebarVisible; [self.animator addCompletion:^(UIViewAnimatingPosition finalPosition) { __strong __typeof(weakSelf) strongSelf = weakSelf; strongSelf.isPanningActive = NO; [strongSelf endSidebarTransition:didBecomeVisible]; [UIViewController attemptRotationToDeviceOrientation]; }]; [self.animator continueAnimationWithTimingParameters:nil durationFactor:SPSidebarAnimationCompletionFactorFull]; } else { CGPoint translation = [gesture translationInView:self.mainView]; CGFloat translationMultiplier = self.isSidebarVisible ? -1 : 1; CGFloat progress = translation.x / SPSidebarWidth * translationMultiplier * self.directionalMultiplier; self.animator.fractionComplete = MAX(SPSidebarAnimationCompletionMin, MIN(SPSidebarAnimationCompletionMax, progress)); } } - (void)rootViewTapped:(UITapGestureRecognizer *)gesture { if (self.isPanningActive) { return; } [self hideSidebarWithAnimation:YES]; } #pragma mark - Panning - (void)beginSidebarTransition:(BOOL)isAppearing { if (isAppearing) { [self.delegate sidebarContainerWillDisplaySidebar:self]; [self ensureSideTableViewInsetsMatchMainViewInsets]; } else { [self.delegate sidebarContainerWillHideSidebar:self]; } [self.sidebarViewController beginAppearanceTransition:isAppearing animated:YES]; } - (void)endSidebarTransition:(BOOL)appeared { if (appeared) { [self.delegate sidebarContainerDidDisplaySidebar:self]; [self.mainView addGestureRecognizer:self.mainViewTapGestureRecognier]; } else { [self.delegate sidebarContainerDidHideSidebar:self]; [self.mainView removeGestureRecognizer:self.mainViewTapGestureRecognier]; } [self.sidebarViewController endAppearanceTransition]; } #pragma mark - RTL Support - (BOOL)isRightToLeft { return UIApplication.sharedApplication.userInterfaceLayoutDirection == UIUserInterfaceLayoutDirectionRightToLeft; } /// The purpose of this method is to normalize calculations, regardless of the writing direction, so that we do not need to duplicate checks. /// /// Rather than checking: /// `isRTL == false && translation.x < 0` OR `isRTL == true ^^ translation.x > 0`, /// /// We can simply check for: /// `translation.x * directionalMultiplier < 0`. /// - (CGFloat)directionalMultiplier { return self.isRightToLeft ? SPDirectionalInverted : SPDirectionalIdentity; } #pragma mark - Public API - (void)toggleSidebar { if (self.isSidebarVisible) { [self hideSidebarWithAnimation:YES]; } else { [self showSidebar]; } } - (void)showSidebar { if (self.isPanningActive || self.isSidebarVisible) { return; } [self beginSidebarTransition:YES]; UIViewPropertyAnimator *animator = [self animatorForSidebarVisibility:YES]; [animator addCompletion:^(UIViewAnimatingPosition finalPosition) { self.isSidebarVisible = YES; [self endSidebarTransition:YES]; }]; [animator startAnimation]; self.animator = animator; } - (void)hideSidebarWithAnimation:(BOOL)animated { if (self.isPanningActive || !self.isSidebarVisible) { return; } [self beginSidebarTransition:NO]; UIViewPropertyAnimator *animator = [self animatorForSidebarVisibility:NO]; [animator addCompletion:^(UIViewAnimatingPosition finalPosition) { self.isSidebarVisible = NO; [self endSidebarTransition:NO]; [UIViewController attemptRotationToDeviceOrientation]; }]; if (animated) { [animator startAnimation]; } else { animator.fractionComplete = 1; [animator continueAnimationWithTimingParameters:nil durationFactor:SPSidebarAnimationCompletionFactorZero]; } self.animator = animator; } - (void)requirePanningToFail { [self.panGestureRecognizer fail]; } @end ```
/content/code_sandbox/Simplenote/Classes/SPSidebarContainerViewController.m
objective-c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
3,368
```objective-c // // SPRatingsHelper.h // Simplenote // // Created by Jorge Leandro Perez on 3/19/15. // #import "WPRatingsHelper.h" @interface SPRatingsHelper : WPRatingsHelper - (void)reloadSettings; - (BOOL)shouldPromptForAppReview; @end ```
/content/code_sandbox/Simplenote/Classes/SPRatingsHelper.h
objective-c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
70
```swift import Foundation import CoreSpotlight import Intents import MobileCoreServices // MARK: - NSUserActivity Convenience Methods // extension NSUserActivity { /// Initializes a UserActivity Instance with a given Activity Type /// /// - Parameters: /// - type: The Activity Type we're representing /// - title: Display text that will show up in Spotlight /// - suggestedInvocationPhrase: Optional hint that shows up whenever the user adds a shortcut. When nil, we'll /// assume the *title* is a valid Suggested Invocation Phrase. /// convenience init(type: ActivityType, title: String, suggestedInvocationPhrase: String? = nil) { self.init(activityType: type.rawValue) self.title = title isEligibleForSearch = true isEligibleForHandoff = false isEligibleForPrediction = true self.suggestedInvocationPhrase = suggestedInvocationPhrase ?? title } } ```
/content/code_sandbox/Simplenote/Classes/NSUserActivity+Simplenote.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
210