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 |
|---|---|---|---|---|---|---|---|---|
```swift
import UIKit
import Social
typealias CompletionBlock = () -> Void
/// Main VC for Simplenote's Share Extension
///
class ShareViewController: UIViewController {
/// This completion handler closure is executed when this VC is dismissed.
///
@objc var dismissalCompletionBlock: CompletionBlock?
// MARK: Private Properties
@IBOutlet private weak var textView: UITextView!
/// Returns the Main App's SimperiumToken
///
private var simperiumToken: String? {
KeychainManager.extensionToken
}
/// Indicates if the Markdown flag should be enabled
///
private var isMarkdown: Bool {
return originalNote?.markdown ?? false
}
/// The extension context data provided from the host app
///
private var context: NSExtensionContext?
/// The original, unmodified note extracted from the NSExtensionContext
///
private var originalNote: Note?
/// Cancel Bar Button
///
private lazy var cancelButton: UIBarButtonItem = {
let cancelTitle = NSLocalizedString("Cancel", comment: "Cancel action on share extension.")
let button = UIBarButtonItem(title: cancelTitle, style: .plain, target: self, action: #selector(cancelWasPressed))
button.accessibilityIdentifier = "Cancel Button"
return button
}()
/// Next Bar Button
///
private lazy var nextButton: UIBarButtonItem = {
let nextButtonTitle = NSLocalizedString("Save", comment: "Save action on share extension.")
let button = UIBarButtonItem(title: nextButtonTitle, style: .plain, target: self, action: #selector(saveWasPressed))
button.accessibilityIdentifier = "Save Button"
return button
}()
// MARK: Initialization
/// Designated Initializer
///
init(context: NSExtensionContext?) {
self.context = context
super.init(nibName: type(of: self).nibName, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: UIViewController Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
setupNavigationBar()
textView.textContainerInset = Constants.textViewInsets
loadContent()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
textView.becomeFirstResponder()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
ensureSimperiumTokenIsValid()
}
}
// MARK: - Actions
//
private extension ShareViewController {
@objc func cancelWasPressed() {
dismissExtension()
}
@objc func saveWasPressed() {
guard let updatedText = textView.text else {
dismissExtension()
return
}
guard updatedText.isEmpty == false else {
// Don't bother saving empty notes.
dismissExtension()
return
}
let updatedNote = Note(content: updatedText, markdown: isMarkdown)
submit(note: updatedNote)
dismissExtension()
}
/// Submits a given Note to the user's Simplenote account
///
func submit(note: Note) {
guard let simperiumToken = simperiumToken else {
return
}
let uploader = Uploader(simperiumToken: simperiumToken)
uploader.send(note)
}
/// Dismiss the extension and call the appropriate completion block
/// from the original `NSExtensionContext`
///
func dismissExtension() {
view.endEditing(true)
dismiss(animated: true, completion: self.dismissalCompletionBlock)
}
}
// MARK: - Token Validation
//
private extension ShareViewController {
func ensureSimperiumTokenIsValid() {
guard isSimperiumTokenInvalid() else {
return
}
displayMissingAccountAlert()
}
func isSimperiumTokenInvalid() -> Bool {
return simperiumToken == nil
}
func displayMissingAccountAlert() {
let title = NSLocalizedString("No Simplenote Account", comment: "Extension Missing Token Alert Title")
let message = NSLocalizedString("Please log into your Simplenote account first by using the Simplenote app.", comment: "Extension Missing Token Alert Title")
let accept = NSLocalizedString("Cancel Share", comment: "Name of button to cancel iOS share extension in missing token alert ")
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let alertAction = UIAlertAction(title: accept, style: .default) { _ in
self.cancelWasPressed()
}
alertController.addAction(alertAction)
present(alertController, animated: true, completion: nil)
}
}
// MARK: - Configuration
//
private extension ShareViewController {
func setupNavigationBar() {
navigationItem.leftBarButtonItem = cancelButton
navigationItem.rightBarButtonItem = nextButton
navigationItem.title = NSLocalizedString("Simplenote", comment: "Title of main share extension view")
}
/// Attempts to extract the Note's Payload from the current ExtensionContext
///
func loadContent() {
guard let context = context else {
fatalError()
}
context.extractNote(from: context) { note in
guard let note = note else {
return
}
self.originalNote = note
self.textView.text = note.content
}
}
}
// MARK: - Constants
//
private struct Constants {
static let textViewInsets = UIEdgeInsets(top: 8.0, left: 12.0, bottom: 8.0, right: 12.0)
}
``` | /content/code_sandbox/SimplenoteShare/ViewControllers/ShareViewController.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 1,158 |
```swift
import UIKit
class SharePresentationController: UIViewController {
private let extensionTransitioningManager: ExtensionTransitioningManager = {
let manager = ExtensionTransitioningManager()
manager.presentDirection = .bottom
manager.dismissDirection = .bottom
return manager
}()
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override open func viewDidLoad() {
super.viewDidLoad()
setupAppearance()
}
override open func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
loadAndPresentMainVC()
}
}
// MARK: - Private Helpers
//
private extension SharePresentationController {
func loadAndPresentMainVC() {
let shareController = ShareViewController(context: extensionContext)
shareController.dismissalCompletionBlock = {
self.extensionContext?.completeRequest(returningItems: nil, completionHandler: nil)
}
let shareNavController = UINavigationController(rootViewController: shareController)
shareNavController.transitioningDelegate = extensionTransitioningManager
shareNavController.modalPresentationStyle = .custom
present(shareNavController, animated: true)
}
}
// MARK: - Appearance Helpers
//
private extension SharePresentationController {
func setupAppearance() {
let navbarAppearance = UINavigationBar.appearance()
navbarAppearance.barTintColor = .simplenoteBackgroundColor
navbarAppearance.barStyle = .default
navbarAppearance.tintColor = .simplenoteTintColor
navbarAppearance.titleTextAttributes = [
.foregroundColor: UIColor.simplenoteNavigationBarTitleColor
]
navbarAppearance.isTranslucent = false
let barButtonTitleAttributes: [NSAttributedString.Key: Any] = [
.foregroundColor: UIColor.simplenoteTintColor
]
let barButtonAppearance = UIBarButtonItem.appearance()
barButtonAppearance.tintColor = .simplenoteTintColor
barButtonAppearance.setTitleTextAttributes(barButtonTitleAttributes, for: .normal)
}
}
``` | /content/code_sandbox/SimplenoteShare/ViewControllers/SharePresentationController.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 399 |
```swift
import UIKit
/// Allows certain presented view controllers to request themselves to be
/// presented at full size instead of inset within the container.
///
protocol ExtensionPresentationTarget {
var shouldFillContentContainer: Bool { get }
}
final class ExtensionPresentationController: UIPresentationController {
// MARK: - Private Properties
private var presentDirection: Direction
private var dismissDirection: Direction
private var keyboardNotificationTokens: [Any]?
private let dimmingView: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = Appearance.dimmingViewBGColor
view.alpha = Constants.zeroAlpha
return view
}()
// MARK: Initializers
init(presentedViewController: UIViewController,
presenting presentingViewController: UIViewController?,
presentDirection: Direction,
dismissDirection: Direction) {
self.presentDirection = presentDirection
self.dismissDirection = dismissDirection
super.init(presentedViewController: presentedViewController, presenting: presentingViewController)
self.keyboardNotificationTokens = self.addKeyboardObservers()
}
deinit {
guard let tokens = keyboardNotificationTokens else {
return
}
removeKeyboardObservers(with: tokens)
}
// MARK: Presentation Controller Overrides
override var frameOfPresentedViewInContainerView: CGRect {
var frame: CGRect = .zero
if let containerView = containerView {
frame.size = size(forChildContentContainer: presentedViewController, withParentContainerSize: containerView.bounds.size)
frame.origin.x = (containerView.frame.width - frame.width) / 2.0
frame.origin.y = (containerView.frame.height - frame.height) / 2.0
}
return frame
}
override func size(forChildContentContainer container: UIContentContainer, withParentContainerSize parentSize: CGSize) -> CGSize {
if let target = container as? ExtensionPresentationTarget,
target.shouldFillContentContainer == true {
return parentSize
}
let widthRatio = traitCollection.verticalSizeClass != .compact ? Appearance.widthRatio : Appearance.widthRatioCompactVertical
let heightRatio = traitCollection.verticalSizeClass != .compact ? Appearance.heightRatio : Appearance.heightRatioCompactVertical
return CGSize(width: (parentSize.width * widthRatio), height: (parentSize.height * heightRatio))
}
override func containerViewWillLayoutSubviews() {
presentedView?.frame = frameOfPresentedViewInContainerView
presentedView?.layer.cornerRadius = Appearance.cornerRadius
presentedView?.clipsToBounds = true
}
override func presentationTransitionWillBegin() {
containerView?.insertSubview(dimmingView, at: 0)
NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: "V:|[dimmingView]|", options: [], metrics: nil, views: ["dimmingView": dimmingView]))
NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: "H:|[dimmingView]|", options: [], metrics: nil, views: ["dimmingView": dimmingView]))
guard let coordinator = presentedViewController.transitionCoordinator else {
dimmingView.alpha = Constants.fullAlpha
return
}
coordinator.animate(alongsideTransition: { _ in
self.dimmingView.alpha = Constants.fullAlpha
})
}
override func dismissalTransitionWillBegin() {
guard let coordinator = presentedViewController.transitionCoordinator else {
dimmingView.alpha = Constants.zeroAlpha
return
}
coordinator.animate(alongsideTransition: { _ in
self.dimmingView.alpha = Constants.zeroAlpha
})
}
}
// MARK: - KeyboardObservable Conformance
//
extension ExtensionPresentationController: KeyboardObservable {
func keyboardWillChangeFrame(beginFrame: CGRect?, endFrame: CGRect?, animationDuration: TimeInterval?, animationCurve: UInt?) {
let keyboardFrame = endFrame ?? .zero
let duration = animationDuration ?? Constants.defaultAnimationDuration
animate(with: presentedView!.convert(keyboardFrame, from: nil), duration: duration, animationCurve: animationCurve)
}
func keyboardDidChangeFrame(beginFrame: CGRect?, endFrame: CGRect?, animationDuration: TimeInterval?, animationCurve: UInt?) {
// TODO:
// We should really animate (again) here, but not doing so. The layout mechanism is broken when called twice.
}
private func animate(with keyboardFrame: CGRect, duration: TimeInterval, animationCurve: UInt?) {
let presentedFrame = frameOfPresentedViewInContainerView
let translatedFrame = getTranslationFrame(keyboardFrame: keyboardFrame, presentedFrame: presentedFrame)
var animationOptions: UIView.AnimationOptions = []
if let animationCurve = animationCurve {
animationOptions = UIView.AnimationOptions(rawValue: animationCurve)
}
UIView.animate(withDuration: duration, delay: 0.0, options: animationOptions, animations: {
self.presentedView?.frame = translatedFrame
})
}
private func getTranslationFrame(keyboardFrame: CGRect, presentedFrame: CGRect) -> CGRect {
let keyboardTopPadding = traitCollection.verticalSizeClass != .compact ? Constants.bottomKeyboardMarginPortrait : Constants.bottomKeyboardMarginLandscape
let keyboardTop = UIScreen.main.bounds.height - (keyboardFrame.size.height + keyboardTopPadding)
let presentedViewBottom = presentedFrame.origin.y + presentedFrame.height
let offset = presentedViewBottom - keyboardTop
guard offset > 0.0 else {
return presentedFrame
}
let newHeight = presentedFrame.size.height - offset
let frame = CGRect(x: presentedFrame.origin.x, y: presentedFrame.origin.y, width: presentedFrame.size.width, height: newHeight)
return frame
}
}
// MARK: - Constants
//
private extension ExtensionPresentationController {
struct Constants {
static let fullAlpha: CGFloat = 1.0
static let zeroAlpha: CGFloat = 0.0
static let defaultAnimationDuration: Double = 0.25
static let bottomKeyboardMarginPortrait: CGFloat = 8.0
static let bottomKeyboardMarginLandscape: CGFloat = 8.0
}
struct Appearance {
static let dimmingViewBGColor = UIColor(white: 0.0, alpha: 0.5)
static let cornerRadius: CGFloat = 4.0
static let widthRatio: CGFloat = 0.90
static let widthRatioCompactVertical: CGFloat = 0.90
static let heightRatio: CGFloat = 0.80
static let heightRatioCompactVertical: CGFloat = 0.80
}
}
``` | /content/code_sandbox/SimplenoteShare/Presentation/ExtensionPresentationController.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 1,383 |
```swift
import UIKit
final class ExtensionTransitioningManager: NSObject {
var presentDirection = Direction.bottom
var dismissDirection = Direction.bottom
}
// MARK: - UIViewControllerTransitioningDelegate Conformance
//
extension ExtensionTransitioningManager: UIViewControllerTransitioningDelegate {
func presentationController(forPresented presented: UIViewController,
presenting: UIViewController?,
source: UIViewController) -> UIPresentationController? {
let presentationController = ExtensionPresentationController(presentedViewController: presented,
presenting: presenting,
presentDirection: presentDirection,
dismissDirection: dismissDirection)
return presentationController
}
func animationController(forPresented presented: UIViewController,
presenting: UIViewController,
source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return ExtensionPresentationAnimator(direction: presentDirection, isPresentation: true)
}
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return ExtensionPresentationAnimator(direction: dismissDirection, isPresentation: false)
}
}
``` | /content/code_sandbox/SimplenoteShare/Presentation/ExtensionTransitioningManager.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 202 |
```swift
import UIKit
/// Direction to transition from/to.
///
/// - left: Enter/leave screen via the left edge.
/// - top: Enter/leave screen via the top edge.
/// - right: Enter/leave screen via the left edge.
/// - bottom: Enter/leave screen via the bottom edge.
///
enum Direction {
case left
case top
case right
case bottom
}
/// Animator that animates the presented View Controller from/to a specific `Direction`.
///
final class ExtensionPresentationAnimator: NSObject {
let direction: Direction
let isPresentation: Bool
init(direction: Direction, isPresentation: Bool) {
self.direction = direction
self.isPresentation = isPresentation
super.init()
}
}
// MARK: - UIViewControllerAnimatedTransitioning Conformance
//
extension ExtensionPresentationAnimator: UIViewControllerAnimatedTransitioning {
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return Constants.animationDuration
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let key = isPresentation ? UITransitionContextViewControllerKey.to : UITransitionContextViewControllerKey.from
let controller = transitionContext.viewController(forKey: key)!
if isPresentation {
transitionContext.containerView.addSubview(controller.view)
}
let presentedFrame = transitionContext.finalFrame(for: controller)
var dismissedFrame = presentedFrame
switch direction {
case .left:
dismissedFrame.origin.x = -presentedFrame.width
case .right:
dismissedFrame.origin.x = transitionContext.containerView.frame.size.width
case .top:
dismissedFrame.origin.y = -presentedFrame.height
case .bottom:
dismissedFrame.origin.y = transitionContext.containerView.frame.size.height
}
let initialFrame = isPresentation ? dismissedFrame : presentedFrame
let finalFrame = isPresentation ? presentedFrame : dismissedFrame
let animationDuration = transitionDuration(using: transitionContext)
controller.view.frame = initialFrame
UIView.animate(withDuration: animationDuration, animations: {
controller.view.frame = finalFrame
}) { finished in
transitionContext.completeTransition(finished)
}
}
}
// MARK: - Constants
//
private struct Constants {
static let animationDuration: Double = 0.33
}
``` | /content/code_sandbox/SimplenoteShare/Presentation/ExtensionPresentationAnimator.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 476 |
```objective-c
//
// TextBundle.h
// TextBundle-Mac
//
// Created by Matteo Rattotti on 22/02/2019.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
extern NSString * const kUTTypeMarkdown;
extern NSString * const kUTTypeTextBundle;
extern NSString * const TextBundleErrorDomain;
typedef NS_ENUM(NSInteger, TextBundleError)
{
TextBundleErrorInvalidFormat,
};
@interface TextBundleWrapper : NSObject
/**
The plain text contents, read from text.* (whereas * is an arbitrary file extension)
*/
@property (strong, nonnull) NSString *text;
/**
File wrapper represeting the whole TextBundle.
*/
@property (readonly, nonatomic) NSFileWrapper *fileWrapper;
/**
File wrapper containing all asset files referenced from the plain text file.
*/
@property (strong, nonnull) NSFileWrapper *assetsFileWrapper;
/**
The version number of the file format. Version 2 (latest) is used as default.
*/
@property (strong) NSNumber *version;
/**
The UTI of the text.* file.
*/
@property (strong) NSString *type;
/**
Whether or not the bundle is a temporary container solely used for exchanging a document between applications. Defaults to false.
*/
@property (strong) NSNumber *transient;
/**
The bundle identifier of the application that created the file.
*/
@property (strong) NSString *creatorIdentifier;
/**
Dictionary of application-specific information. Application-specific information must be stored inside a nested dictionary.
The dictionary is referenced by a key using the application bundle identifier (e.g. com.example.myapp).
This dictionary should contain at least a version number to ensure backwards compatibility.
Example:
"com.example.myapp": {
"version": 9,
"customKey": "aCustomValue"
}
*/
@property (strong) NSMutableDictionary *metadata;
/**
Returns true if type name is conforming to the TextBundle type
@param typeName The string that identifies the file type.
@return True if type name is conforming to the textbundle type
*/
+ (BOOL)isTextBundleType:(NSString *)typeName;
/**
Initialize a TextBundleWrapper instance from URL
@param url URL of the file the TextBundleWrapper is to represent.
@param options flags for reading the TextBundleWrapper at url. See NSFileWrapperReadingOptions for possible values.
@param error If an error occurs, upon return contains an NSError object that describes the problem. Pass NULL if you do not want error information.
@return A new TextBundleWrapper for the content at url.
*/
- (instancetype)initWithContentsOfURL:(NSURL *)url options:(NSFileWrapperReadingOptions)options error:(NSError **)error;
/**
Initialize a TextBundleWrapper instance from a NSFileWrapper
@param fileWrapper The NSFileWrapper representing the TextBundle
@param error If an error occurs, upon return contains an NSError object that describes the problem. Pass NULL if you do not want error information.
@return A new TextBundleWrapper for the content of the fileWrapper.
*/
- (instancetype)initWithFileWrapper:(NSFileWrapper *)fileWrapper error:(NSError **)error;
/**
Writes the TextBundleWrapper content to a given file-system URL.
@param url URL of the file to which the TextBundleWrapper's contents are written.
@param options flags for writing to the file located at url. See NSFileWrapperWritingOptions for possible values.
@param originalContentsURL The location of a previous revision of the contents being written.
The default implementation of this method attempts to avoid unnecessary I/O by writing hard links to regular files
instead of actually writing out their contents when the contents have not changed.
@param error If an error occurs, upon return contains an NSError object that describes the problem. Pass NULL if you do not want error information.
@return YES when the write operation is successful. If not successful, returns NO after setting error to an NSError object that describes the reason why the TextBundleWrapper's contents could not be written.
*/
- (BOOL)writeToURL:(NSURL *)url options:(NSFileWrapperWritingOptions)options originalContentsURL:(nullable NSURL *)originalContentsURL error:(NSError **)error;
/**
Return the filewrapper represeting an asset or nil if there is no asset named with filename
@param filename A filename in the asset/ folder
@return A NSFilewrapper represeting filename or nil it the file doesn't exist
*/
- (NSFileWrapper *)fileWrapperForAssetFilename:(NSString *)filename;
/**
Add a NSFileWrapper to the TextBundleWrapper's assetFileWrapper.
If a file have the same name of an exiting file the name will be changed and if the file has the same content this method will do nothing.
@param assetFileWrapper A NSFileWrapper to add to the TextBundleWrapper's assets
@return The final filename of the added asset.
*/
- (NSString *)addAssetFileWrapper:(NSFileWrapper *)assetFileWrapper;
@end
NS_ASSUME_NONNULL_END
``` | /content/code_sandbox/SimplenoteShare/Tools/TextBundleWrapper.h | objective-c | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 1,022 |
```objective-c
//
// TextBundle.m
// TextBundle-Mac
//
// Created by Matteo Rattotti on 22/02/2019.
//
#import "TextBundleWrapper.h"
#import <CoreServices/CoreServices.h>
#import <UniformTypeIdentifiers/UniformTypeIdentifiers.h>
// Filenames constants
NSString * const kTextBundleInfoFileName = @"info.json";
NSString * const kTextBundleAssetsFileName = @"assets";
// UTI constants
NSString * const kUTTypeMarkdown = @"net.daringfireball.markdown";
NSString * const kUTTypeTextBundle = @"org.textbundle.package";
// Metadata constants
NSString * const kTextBundleVersion = @"version";
NSString * const kTextBundleType = @"type";
NSString * const kTextBundleTransient = @"transient";
NSString * const kTextBundleCreatorIdentifier = @"creatorIdentifier";
// Error constants
NSString * const TextBundleErrorDomain = @"TextBundleErrorDomain";
@implementation TextBundleWrapper
+ (BOOL)isTextBundleType:(NSString *)typeName
{
UTType *typeTextBundle = [UTType importedTypeWithIdentifier:kTextBundleType];
UTType *typeForName = [UTType importedTypeWithIdentifier:typeName];
return [typeForName conformsToType:typeTextBundle];
}
- (instancetype)init
{
self = [super init];
if (self) {
// Setting some default values
self.metadata = [NSMutableDictionary dictionary];
self.version = @(2);
self.type = kUTTypeMarkdown;
self.transient = @(NO);
self.assetsFileWrapper = [[NSFileWrapper alloc] initDirectoryWithFileWrappers:@{}];
self.assetsFileWrapper.preferredFilename = kTextBundleAssetsFileName;
}
return self;
}
- (instancetype)initWithContentsOfURL:(NSURL *)url options:(NSFileWrapperReadingOptions)options error:(NSError **)error
{
self = [self init];
if (self) {
BOOL success = [self readFromURL:url options:options error:error];
if (!success) {
return nil;
}
}
return self;
}
- (instancetype)initWithFileWrapper:(NSFileWrapper *)fileWrapper error:(NSError **)error
{
self = [self init];
if (self) {
BOOL success = [self readFromFilewrapper:fileWrapper error:error];
if (!success) {
return nil;
}
}
return self;
}
#pragma mark - Writing
- (NSFileWrapper *)fileWrapper
{
if (!self.text) {
return nil;
}
NSFileWrapper *textBundleFileWrapper = [[NSFileWrapper alloc] initDirectoryWithFileWrappers:@{}];
// Text
[textBundleFileWrapper addRegularFileWithContents:[self.text dataUsingEncoding:NSUTF8StringEncoding] preferredFilename:[self textFilenameForType:self.type]];
// Info
[textBundleFileWrapper addRegularFileWithContents:[self jsonDataForMetadata:self.metadata] preferredFilename:kTextBundleInfoFileName];
// Assets
if (self.assetsFileWrapper && self.assetsFileWrapper.fileWrappers.count) {
[textBundleFileWrapper addFileWrapper:self.assetsFileWrapper];
}
return textBundleFileWrapper;
}
- (BOOL)writeToURL:(NSURL *)url options:(NSFileWrapperWritingOptions)options originalContentsURL:(nullable NSURL *)originalContentsURL error:(NSError **)error
{
return [self.fileWrapper writeToURL:url options:options originalContentsURL:originalContentsURL error:error];
}
#pragma mark - Reading
- (BOOL)readFromURL:(NSURL *)url options:(NSFileWrapperReadingOptions)options error:(NSError **)error
{
NSError *readError = nil;
NSFileWrapper *textBundleFileWrapper = [[NSFileWrapper alloc] initWithURL:url options:options error:&readError];
if (readError) {
if (error) { *error = readError; }
return NO;
}
return [self readFromFilewrapper:textBundleFileWrapper error:error];
}
- (BOOL)readFromFilewrapper:(NSFileWrapper *)textBundleFileWrapper error:(NSError **)error
{
// Info
NSFileWrapper *infoFileWrapper = [[textBundleFileWrapper fileWrappers] objectForKey:kTextBundleInfoFileName];
if (infoFileWrapper) {
NSData *fileData = [infoFileWrapper regularFileContents];
NSError *jsonReadError = nil;
NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:fileData options:0 error:&jsonReadError];
if (jsonReadError) {
if (error) { *error = jsonReadError; }
return NO;
}
self.metadata = [jsonObject mutableCopy];
self.version = self.metadata[kTextBundleVersion];
self.type = self.metadata[kTextBundleType];
self.transient = self.metadata[kTextBundleTransient];
self.creatorIdentifier = self.metadata[kTextBundleCreatorIdentifier];
[self.metadata removeObjectForKey:kTextBundleVersion];
[self.metadata removeObjectForKey:kTextBundleType];
[self.metadata removeObjectForKey:kTextBundleTransient];
[self.metadata removeObjectForKey:kTextBundleCreatorIdentifier];
}
else {
if (error) {
*error = [NSError errorWithDomain:TextBundleErrorDomain code:TextBundleErrorInvalidFormat userInfo:nil];
}
return NO;
}
// Text
NSFileWrapper *textFileWrapper = [[textBundleFileWrapper fileWrappers] objectForKey:[self textFileNameInFileWrapper:textBundleFileWrapper]];
if (textFileWrapper) {
self.text = [[NSString alloc] initWithData:textFileWrapper.regularFileContents encoding:NSUTF8StringEncoding];
}
else {
if (error) {
*error = [NSError errorWithDomain:TextBundleErrorDomain code:TextBundleErrorInvalidFormat userInfo:nil];
}
return NO;
}
// Assets
NSFileWrapper *assetsWrapper = [[textBundleFileWrapper fileWrappers] objectForKey:kTextBundleAssetsFileName];
if (assetsWrapper) {
self.assetsFileWrapper = assetsWrapper;
}
return YES;
}
#pragma mark - Text
- (NSString *)textFileNameInFileWrapper:(NSFileWrapper*)fileWrapper
{
// Finding the text.* file inside the .textbundle
__block NSString *filename = nil;
[[fileWrapper fileWrappers] enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSFileWrapper * obj, BOOL *stop)
{
if([[obj.filename lowercaseString] hasPrefix:@"text"]) {
filename = obj.filename;
}
}];
return filename;
}
- (NSString *)textFilenameForType:(NSString *)type
{
UTType *uttype = [UTType importedTypeWithIdentifier:type];
return [@"text" stringByAppendingPathExtension:uttype.preferredFilenameExtension];
}
#pragma mark - Assets
- (NSFileWrapper *)fileWrapperForAssetFilename:(NSString *)filename
{
__block NSFileWrapper *fileWrapper = nil;
[[self.assetsFileWrapper fileWrappers] enumerateKeysAndObjectsUsingBlock:^(NSString * _Nonnull key, NSFileWrapper * _Nonnull obj, BOOL * _Nonnull stop) {
if ([obj.filename isEqualToString:filename] || [obj.preferredFilename isEqualToString:filename]) {
fileWrapper = obj;
}
}];
return fileWrapper;
}
- (NSString *)addAssetFileWrapper:(NSFileWrapper *)assetFileWrapper
{
NSString *originalFilename = assetFileWrapper.filename ?: assetFileWrapper.preferredFilename;
NSString *filename = originalFilename;
NSUInteger filenameCount = 1;
BOOL shouldAddFileWrapper = YES;
NSArray *currentFilenames = [self.assetsFileWrapper.fileWrappers allKeys];
while ([currentFilenames containsObject:filename]) {
NSFileWrapper *existingFileWrapper = [self.assetsFileWrapper fileWrappers][filename];
// Same filename and same data, we can skip adding this file
if ([assetFileWrapper.regularFileContents isEqualToData:existingFileWrapper.regularFileContents]) {
shouldAddFileWrapper = NO;
break;
}
// Same filename, different data, changing the name
else {
filenameCount++;
filename = [self filenameWithIncreasedNumberCountForFilename:originalFilename currentCount:filenameCount];
assetFileWrapper.filename = filename;
assetFileWrapper.preferredFilename = filename;
}
}
if (shouldAddFileWrapper) {
filename = [self.assetsFileWrapper addFileWrapper:assetFileWrapper];
}
return filename;
}
#pragma mark - Metadata
- (NSData *)jsonDataForMetadata:(NSDictionary *)metadata
{
NSMutableDictionary *allMetadata = [NSMutableDictionary dictionary];
[allMetadata addEntriesFromDictionary:metadata];
if (self.version) { allMetadata[kTextBundleVersion] = self.version; }
if (self.type) { allMetadata[kTextBundleType] = self.type; }
if (self.transient) { allMetadata[kTextBundleTransient] = self.transient; }
if (self.creatorIdentifier) { allMetadata[kTextBundleCreatorIdentifier] = self.creatorIdentifier; }
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:allMetadata
options:NSJSONWritingPrettyPrinted
error:nil];
return jsonData;
}
#pragma mark - String Utils
- (NSString *)filenameWithIncreasedNumberCountForFilename:(NSString *)filename currentCount:(NSInteger)currentCount
{
NSString* pathNoExt = [filename stringByDeletingPathExtension];
NSString* extension = [filename pathExtension];
NSString *newFilename = [NSString stringWithFormat:@"%@ %ld", pathNoExt, (long)currentCount];
if (extension && ![extension isEqualToString:@""])
{
newFilename = [newFilename stringByAppendingPathExtension:extension];
}
return newFilename;
}
@end
``` | /content/code_sandbox/SimplenoteShare/Tools/TextBundleWrapper.m | objective-c | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 2,101 |
```swift
import Foundation
// MARK: - NSExtensionContext's Simplenote Methods
//
extension NSExtensionContext {
/// Returns the AttributedContentText stored in the (first) ExtensionItem
///
var attributedContentText: NSAttributedString? {
guard let item = inputItems.first as? NSExtensionItem else {
return nil
}
return item.attributedContentText
}
/// Returns the Item Providers of the specified Type
///
func itemProviders(ofType type: String) -> [NSItemProvider] {
guard let item = inputItems.first as? NSExtensionItem, let providers = item.attachments else {
return []
}
return providers.filter { provider in
return provider.hasItemConformingToTypeIdentifier(type)
}
}
/// Extracts the Note from the current Extension Context
///
func extractNote(from extensionContext: NSExtensionContext, onCompletion: @escaping (Note?) -> Void) {
guard let extractor = Extractors.extractor(for: extensionContext) else {
onCompletion(nil)
return
}
extractor.extractNote(from: extensionContext) { note in
DispatchQueue.main.async {
onCompletion(note)
}
}
}
}
``` | /content/code_sandbox/SimplenoteShare/Extensions/NSExtensionContext+Simplenote.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 258 |
```swift
import Foundation
/// Encapsulates NSURLSessionConfiguration Helpers
///
extension URLSessionConfiguration {
/// Returns a new Background Session Configuration, with a random identifier.
///
class func backgroundSessionConfigurationWithRandomizedIdentifier() -> URLSessionConfiguration {
let identifier = kShareExtensionGroupName + "." + UUID().uuidString
let configuration = URLSessionConfiguration.background(withIdentifier: identifier)
configuration.sharedContainerIdentifier = kShareExtensionGroupName
return configuration
}
}
``` | /content/code_sandbox/SimplenoteShare/Extensions/NSURLSessionConfiguration+Extensions.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 94 |
```swift
import Foundation
import UIKit
// MARK: - Simplenote's Theme
//
@objc
class SPUserInterface: NSObject {
/// Ladies and gentlemen, this is a singleton.
///
@objc
static let shared = SPUserInterface()
/// Indicates if the User Interface is in Dark Mode
///
@objc
static var isDark: Bool {
UITraitCollection.current.userInterfaceStyle == .dark
}
}
``` | /content/code_sandbox/SimplenoteShare/Themes/SPUserInterface.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 95 |
```swift
import Foundation
import MobileCoreServices
import UniformTypeIdentifiers
// MARK: - PlainTextExtractor
//
struct PlainTextExtractor: Extractor {
/// Accepted File Extension
///
let acceptedType = UTType.plainText.identifier
/// Indicates if a given Extension Context can be handled by the Extractor
///
func canHandle(context: NSExtensionContext) -> Bool {
return context.itemProviders(ofType: acceptedType).isEmpty == false
}
/// Extracts a Note entity contained within a given Extension Context (If possible!)
///
func extractNote(from context: NSExtensionContext, onCompletion: @escaping (Note?) -> Void) {
guard let provider = context.itemProviders(ofType: acceptedType).first else {
onCompletion(nil)
return
}
provider.loadItem(forTypeIdentifier: acceptedType, options: nil) { (payload, _) in
guard let content = payload as? String else {
onCompletion(nil)
return
}
let note = Note(content: content)
onCompletion(note)
}
}
}
``` | /content/code_sandbox/SimplenoteShare/Extractors/PlainTextExtractor.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 231 |
```swift
import Foundation
import MobileCoreServices
import ZIPFoundation
import UniformTypeIdentifiers
// MARK: - URLExtractor
//
struct URLExtractor: Extractor {
/// Accepted File Extension
///
let acceptedType = UTType.url.identifier
/// Indicates if a given Extension Context can be handled by the Extractor
///
func canHandle(context: NSExtensionContext) -> Bool {
return context.itemProviders(ofType: acceptedType).isEmpty == false
}
/// Extracts a Note entity contained within a given Extension Context (If possible!)
///
func extractNote(from context: NSExtensionContext, onCompletion: @escaping (Note?) -> Void) {
guard let provider = context.itemProviders(ofType: acceptedType).first else {
onCompletion(nil)
return
}
provider.loadItem(forTypeIdentifier: acceptedType, options: nil) { (payload, _) in
guard let url = payload as? URL else {
onCompletion(nil)
return
}
let note = self.loadNote(from: url) ?? self.buildExternalLinkNote(with: url, context: context)
onCompletion(note)
}
}
}
// MARK: - Loading Notes from a file!
//
private extension URLExtractor {
/// Loads the contents from the specified file, and returns a Note instance with its contents
///
func loadNote(from url: URL) -> Note? {
guard let `extension` = PathExtension(rawValue: url.pathExtension) else {
return nil
}
switch `extension` {
case .bearnote, .textpack:
return loadTextPack(from: url)
case .textbundle:
return loadTextBundle(from: url)
case .text, .txt:
return loadContents(from: url)
case .markdown, .md:
return loadContents(from: url, isMarkdown: true)
}
}
/// Returns a Note matching the payload of a given TextPack file
///
func loadTextPack(from url: URL) -> Note? {
guard let temporaryDirectoryURL = try? FileManager.default.url(for: .itemReplacementDirectory,
in: .userDomainMask,
appropriateFor: url,
create: true) else {
return nil
}
defer {
try? FileManager.default.removeItem(at: temporaryDirectoryURL)
}
do {
try FileManager.default.unzipItem(at: url, to: temporaryDirectoryURL)
let unzippedBundleURL = temporaryDirectoryURL.appendingPathComponent(url.lastPathComponent)
return loadTextBundle(from: unzippedBundleURL)
} catch {
NSLog("TextPack opening failed: \(error.localizedDescription)")
return nil
}
}
/// Returns a Note matching the payload of a given TextBundle file
///
/// - NOTE: We're always setting the markdown flag to true. Several 3rd party apps are using TextBundle, zipped,
/// without proper Markdown extensions.
///
func loadTextBundle(from url: URL) -> Note {
let bundleWrapper = TextBundleWrapper(contentsOf: url, options: .immediate, error: nil)
return Note(content: bundleWrapper.text, markdown: true)
}
/// Returns a Note matching the payload of a given text file
///
func loadContents(from url: URL, isMarkdown: Bool = false) -> Note? {
guard let content = try? String(contentsOf: url) else {
return nil
}
return Note(content: content, markdown: isMarkdown)
}
}
// MARK: - Fallback: Handling external URL(s)
//
private extension URLExtractor {
/// Builds a Note for an external link
///
func buildExternalLinkNote(with url: URL, context: NSExtensionContext) -> Note? {
guard url.isFileURL == false else {
return nil
}
var content = ""
if let payload = context.attributedContentText?.string {
content += payload + "\n\n"
}
content += "[" + url.absoluteString + "]"
return Note(content: content)
}
}
// MARK: - Path Extensions
//
private enum PathExtension: String {
case bearnote
case markdown
case md
case textbundle
case textpack
case text
case txt
}
``` | /content/code_sandbox/SimplenoteShare/Extractors/URLExtractor.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 913 |
```swift
import Foundation
// MARK: - Extractors: Convenience Struct that manages access to all of the known Extractors.
//
struct Extractors {
/// All of the known Extractors
///
private static let extractors: [Extractor] = [
URLExtractor(),
PlainTextExtractor()
]
/// Returns the Extractor that can handle a given Extension Context (if any)
///
static func extractor(for extensionContext: NSExtensionContext) -> Extractor? {
return extractors.first {
$0.canHandle(context: extensionContext)
}
}
}
``` | /content/code_sandbox/SimplenoteShare/Extractors/Extractors.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 120 |
```swift
import Foundation
// MARK: - Extractor
//
protocol Extractor {
/// Accepted File Extension
///
var acceptedType: String { get }
/// Indicates if a given Extension Context can be handled by the Extractor
///
func canHandle(context: NSExtensionContext) -> Bool
/// Extracts a Note entity contained within a given Extension Context (If possible!)
///
func extractNote(from context: NSExtensionContext, onCompletion: @escaping (Note?) -> Void)
}
``` | /content/code_sandbox/SimplenoteShare/Extractors/Extractor.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 106 |
```objective-c
//
// Use this file to import your target's public headers that you would like to expose to Swift.
//
#import "Foundation/Foundation.h"
#import "SPConstants.h"
``` | /content/code_sandbox/SimplenoteIntents/Simplenote-Intents-Bridging-Header.h | objective-c | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 36 |
```swift
//
// IntentsError.swift
// SimplenoteIntents
//
// Created by Charlie Scheer on 5/3/24.
//
import Foundation
enum IntentsError: Error {
case couldNotFetchNotes
case couldNotFetchTags
var title: String {
switch self {
case .couldNotFetchNotes:
return NSLocalizedString("Could not fetch Notes", comment: "Note fetch error title")
case .couldNotFetchTags:
return NSLocalizedString("Could not fetch Tags", comment: "Tag fetch error title")
}
}
var message: String {
switch self {
case .couldNotFetchNotes:
return NSLocalizedString("Attempt to fetch notes failed. Please try again later.", comment: "Data Fetch error message")
case .couldNotFetchTags:
return NSLocalizedString("Attempt to fetch tags failed. Please try again later.", comment: "Data Fetch error message")
}
}
}
``` | /content/code_sandbox/SimplenoteIntents/IntentsError.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 201 |
```swift
//
// IntentsConstants.swift
// Simplenote
//
// Created by Charlie Scheer on 5/2/24.
//
import Foundation
struct IntentsConstants {
static let noteIdentifierKey = "OpenNoteIntentHandlerIdentifierKey"
static let recoveryMessage = NSLocalizedString("Will attempt to recover shortcut content on next launch", comment: "Alerting users that we will attempt to restore lost content on next launch")
}
``` | /content/code_sandbox/SimplenoteIntents/IntentsConstants.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 92 |
```swift
import Intents
import CoreData
class IntentHandler: INExtension {
override func handler(for intent: INIntent) -> Any {
switch intent {
case is NoteWidgetIntent:
return NoteWidgetIntentHandler()
case is ListWidgetIntent:
return ListWidgetIntentHandler()
case is OpenNewNoteIntent:
return OpenNewNoteIntentHandler()
case is OpenNoteIntent:
return OpenNoteIntentHandler()
case is AppendNoteIntent:
return AppendNoteIntentHandler()
case is CreateNewNoteIntent:
return CreateNewNoteIntentHandler()
case is FindNoteIntent:
return FindNoteIntentHandler()
case is CopyNoteContentIntent:
return CopyNoteContentIntentHandler()
case is FindNoteWithTagIntent:
return FindNoteWithTagIntentHandler()
default:
return self
}
}
}
``` | /content/code_sandbox/SimplenoteIntents/IntentHandler.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 178 |
```swift
//
// FindNoteIntentHandler.swift
// SimplenoteIntents
//
// Created by Charlie Scheer on 5/9/24.
//
import Intents
class FindNoteIntentHandler: NSObject, FindNoteIntentHandling {
let coreDataWrapper = ExtensionCoreDataWrapper()
func resolveNote(for intent: FindNoteIntent) async -> IntentNoteResolutionResult {
// If the user has already selected a note return that note with success
if let selectedNote = intent.note {
return IntentNoteResolutionResult.success(with: selectedNote)
}
guard let content = intent.content else {
return IntentNoteResolutionResult.needsValue()
}
return IntentNoteResolutionResult.resolveIntentNote(for: content, in: coreDataWrapper)
}
func provideNoteOptionsCollection(for intent: FindNoteIntent) async throws -> INObjectCollection<IntentNote> {
let intentNotes = try IntentNote.allNotes(in: coreDataWrapper)
return INObjectCollection(items: intentNotes)
}
func handle(intent: FindNoteIntent) async -> FindNoteIntentResponse {
guard let intentNote = intent.note else {
return FindNoteIntentResponse(code: .failure, userActivity: nil)
}
let success = FindNoteIntentResponse(code: .success, userActivity: nil)
success.note = intentNote
return success
}
}
``` | /content/code_sandbox/SimplenoteIntents/Intent Handlers/FindNoteIntentHandler.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 290 |
```swift
//
// NoteWidgetIntentHandler.swift
// Simplenote
//
// Created by Charlie Scheer on 5/2/24.
//
import Intents
class NoteWidgetIntentHandler: NSObject, NoteWidgetIntentHandling {
let coreDataWrapper = ExtensionCoreDataWrapper()
func provideNoteOptionsCollection(for intent: NoteWidgetIntent, with completion: @escaping (INObjectCollection<WidgetNote>?, Error?) -> Void) {
guard WidgetDefaults.shared.loggedIn else {
completion(nil, WidgetError.appConfigurationError)
return
}
guard let notes = coreDataWrapper.resultsController()?.notes() else {
completion(nil, WidgetError.fetchError)
return
}
let collection = widgetNoteInObjectCollection(from: notes)
completion(collection, nil)
}
private func widgetNoteInObjectCollection(from notes: [Note]) -> INObjectCollection<WidgetNote> {
let widgetNotes = notes.map({ note in
WidgetNote(identifier: note.simperiumKey, display: note.title)
})
return INObjectCollection(items: widgetNotes)
}
func defaultNote(for intent: NoteWidgetIntent) -> WidgetNote? {
guard WidgetDefaults.shared.loggedIn,
let note = coreDataWrapper.resultsController()?.firstNote() else {
return nil
}
return WidgetNote(identifier: note.simperiumKey, display: note.title)
}
}
``` | /content/code_sandbox/SimplenoteIntents/Intent Handlers/NoteWidgetIntentHandler.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 295 |
```swift
import Intents
class CreateNewNoteIntentHandler: NSObject, CreateNewNoteIntentHandling {
let coreDataWrapper = ExtensionCoreDataWrapper()
func handle(intent: CreateNewNoteIntent) async -> CreateNewNoteIntentResponse {
guard let content = intent.content,
let token = KeychainManager.extensionToken else {
return CreateNewNoteIntentResponse(code: .failure, userActivity: nil)
}
do {
_ = try await Uploader(simperiumToken: token).send(note(with: content))
return CreateNewNoteIntentResponse(code: .success, userActivity: nil)
} catch {
RecoveryArchiver().archiveContent(content)
return CreateNewNoteIntentResponse.failure(failureReason: "\(error.localizedDescription) - \(IntentsConstants.recoveryMessage)")
}
}
private func note(with content: String) -> Note {
let note = Note(context: coreDataWrapper.context())
note.creationDate = .now
note.modificationDate = .now
note.content = content
return note
}
}
``` | /content/code_sandbox/SimplenoteIntents/Intent Handlers/CreateNewNoteIntentHandler.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 223 |
```swift
import Intents
class AppendNoteIntentHandler: NSObject, AppendNoteIntentHandling {
let coreDataWrapper = ExtensionCoreDataWrapper()
func resolveContent(for intent: AppendNoteIntent) async -> INStringResolutionResult {
guard let content = intent.content else {
return INStringResolutionResult.needsValue()
}
return INStringResolutionResult.success(with: content)
}
func resolveNote(for intent: AppendNoteIntent) async -> IntentNoteResolutionResult {
IntentNoteResolutionResult.resolve(intent.note, in: coreDataWrapper)
}
func provideNoteOptionsCollection(for intent: AppendNoteIntent) async throws -> INObjectCollection<IntentNote> {
let intentNotes = try IntentNote.allNotes(in: coreDataWrapper)
return INObjectCollection(items: intentNotes)
}
func handle(intent: AppendNoteIntent) async -> AppendNoteIntentResponse {
guard let identifier = intent.note?.identifier,
let content = intent.content,
let note = coreDataWrapper.resultsController()?.note(forSimperiumKey: identifier),
let token = KeychainManager.extensionToken else {
return AppendNoteIntentResponse(code: .failure, userActivity: nil)
}
do {
let existingContent = try await downloadNoteContent(for: identifier, token: token) ?? String()
note.content = existingContent + "\n\(content)"
try await uploadNoteContent(note, token: token)
return AppendNoteIntentResponse(code: .success, userActivity: nil)
} catch {
return handleFailure(with: error, content: content)
}
}
private func downloadNoteContent(for identifier: String, token: String) async throws -> String? {
let downloader = Downloader(simperiumToken: token)
return try await downloader.getNoteContent(for: identifier)
}
private func uploadNoteContent(_ note: Note, token: String) async throws {
let uploader = Uploader(simperiumToken: token)
_ = try await uploader.send(note)
}
private func handleFailure(with error: Error, content: String) -> AppendNoteIntentResponse {
RecoveryArchiver().archiveContent(content)
return AppendNoteIntentResponse.failure(failureReason: "\(error.localizedDescription) - \(IntentsConstants.recoveryMessage)")
}
}
``` | /content/code_sandbox/SimplenoteIntents/Intent Handlers/AppendNoteIntentHandler.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 479 |
```swift
//
// ListWidgetIntentHandler.swift
// Simplenote
//
// Created by Charlie Scheer on 5/2/24.
//
import Intents
class ListWidgetIntentHandler: NSObject, ListWidgetIntentHandling {
let coreDataWrapper = ExtensionCoreDataWrapper()
func provideTagOptionsCollection(for intent: ListWidgetIntent, with completion: @escaping (INObjectCollection<WidgetTag>?, Error?) -> Void) {
guard WidgetDefaults.shared.loggedIn else {
completion(nil, WidgetError.appConfigurationError)
return
}
guard let tags = coreDataWrapper.resultsController()?.tags() else {
completion(nil, WidgetError.fetchError)
return
}
// Return collection to intents
let collection = tagNoteInObjectCollection(from: tags)
completion(collection, nil)
}
private func tagNoteInObjectCollection(from tags: [Tag]) -> INObjectCollection<WidgetTag> {
var items = [WidgetTag(kind: .allNotes)]
tags.forEach { tag in
let tag = WidgetTag(kind: .tag, name: tag.name)
tag.kind = .tag
items.append(tag)
}
return INObjectCollection(items: items)
}
func defaultTag(for intent: ListWidgetIntent) -> WidgetTag? {
WidgetTag(kind: .allNotes)
}
}
``` | /content/code_sandbox/SimplenoteIntents/Intent Handlers/ListWidgetIntentHandler.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 286 |
```swift
//
// OpenNoteIntentHandler.swift
// Simplenote
//
// Created by Charlie Scheer on 5/2/24.
//
import Intents
class OpenNoteIntentHandler: NSObject, OpenNoteIntentHandling {
let coreDataWrapper = ExtensionCoreDataWrapper()
func resolveNote(for intent: OpenNoteIntent) async -> IntentNoteResolutionResult {
IntentNoteResolutionResult.resolve(intent.note, in: coreDataWrapper)
}
func provideNoteOptionsCollection(for intent: OpenNoteIntent) async throws -> INObjectCollection<IntentNote> {
let intentNotes = try IntentNote.allNotes(in: coreDataWrapper)
return INObjectCollection(items: intentNotes)
}
func handle(intent: OpenNoteIntent) async -> OpenNoteIntentResponse {
guard let identifier = intent.note?.identifier else {
return OpenNoteIntentResponse(code: .failure, userActivity: nil)
}
let activity = NSUserActivity(activityType: ActivityType.openNoteShortcut.rawValue)
activity.userInfo = [IntentsConstants.noteIdentifierKey: identifier]
return OpenNoteIntentResponse(code: .continueInApp, userActivity: activity)
}
}
``` | /content/code_sandbox/SimplenoteIntents/Intent Handlers/OpenNoteIntentHandler.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 245 |
```swift
//
// CopyNoteContentIntentHandler.swift
// SimplenoteIntents
//
// Created by Charlie Scheer on 5/9/24.
//
import Intents
class CopyNoteContentIntentHandler: NSObject, CopyNoteContentIntentHandling {
let coreDataWrapper = ExtensionCoreDataWrapper()
func provideNoteOptionsCollection(for intent: CopyNoteContentIntent) async throws -> INObjectCollection<IntentNote> {
let intentNotes = try IntentNote.allNotes(in: coreDataWrapper)
return INObjectCollection(items: intentNotes)
}
func handle(intent: CopyNoteContentIntent) async -> CopyNoteContentIntentResponse {
guard let note = intent.note else {
return CopyNoteContentIntentResponse(code: .unspecified, userActivity: nil)
}
guard let identifier = note.identifier,
let content = coreDataWrapper.resultsController()?.note(forSimperiumKey: identifier)?.content else {
return CopyNoteContentIntentResponse(code: .failure, userActivity: nil)
}
let response = CopyNoteContentIntentResponse(code: .success, userActivity: nil)
response.noteContent = content
return response
}
}
``` | /content/code_sandbox/SimplenoteIntents/Intent Handlers/CopyNoteContentIntentHandler.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 248 |
```swift
//
// OpenNewNoteIntentHandler.swift
// Simplenote
//
// Created by Charlie Scheer on 5/2/24.
//
import Intents
class OpenNewNoteIntentHandler: NSObject, OpenNewNoteIntentHandling {
func handle(intent: OpenNewNoteIntent) async -> OpenNewNoteIntentResponse {
OpenNewNoteIntentResponse(code: .continueInApp, userActivity: nil)
}
}
``` | /content/code_sandbox/SimplenoteIntents/Intent Handlers/OpenNewNoteIntentHandler.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 92 |
```swift
//
// FindNoteWithTagIntentHandler.swift
// SimplenoteIntents
//
// Created by Charlie Scheer on 5/9/24.
//
import Intents
class FindNoteWithTagIntentHandler: NSObject, FindNoteWithTagIntentHandling {
let coreDataWrapper = ExtensionCoreDataWrapper()
func resolveNote(for intent: FindNoteWithTagIntent) async -> IntentNoteResolutionResult {
if let selectedNote = intent.note {
return IntentNoteResolutionResult.success(with: selectedNote)
}
guard let selectedTag = intent.tag else {
return IntentNoteResolutionResult.needsValue()
}
return IntentNoteResolutionResult.resolveIntentNote(forTag: selectedTag, in: coreDataWrapper)
}
func provideTagOptionsCollection(for intent: FindNoteWithTagIntent) async throws -> INObjectCollection<IntentTag> {
let tags = try IntentTag.allTags(in: coreDataWrapper)
return INObjectCollection(items: tags)
}
func handle(intent: FindNoteWithTagIntent) async -> FindNoteWithTagIntentResponse {
guard let note = intent.note else {
return FindNoteWithTagIntentResponse(code: .failure, userActivity: nil)
}
let response = FindNoteWithTagIntentResponse(code: .success, userActivity: nil)
response.note = note
return response
}
}
``` | /content/code_sandbox/SimplenoteIntents/Intent Handlers/FindNoteWithTagIntentHandler.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 282 |
```swift
//
// IntentNote+Helpers.swift
// SimplenoteIntents
//
// Created by Charlie Scheer on 5/8/24.
//
import Intents
extension IntentNoteResolutionResult {
static func resolve(_ intentNote: IntentNote?, in coreDataWrapper: ExtensionCoreDataWrapper) -> IntentNoteResolutionResult {
guard let intentNote = intentNote,
let identifier = intentNote.identifier else {
return IntentNoteResolutionResult.needsValue()
}
guard coreDataWrapper.resultsController()?.noteExists(forSimperiumKey: identifier) == true else {
return IntentNoteResolutionResult.unsupported()
}
return IntentNoteResolutionResult.success(with: intentNote)
}
static func resolveIntentNote(for content: String, in coreDataWrapper: ExtensionCoreDataWrapper) -> IntentNoteResolutionResult {
guard let notes = coreDataWrapper.resultsController()?.notes() else {
return IntentNoteResolutionResult.unsupported()
}
let filteredNotes = notes.filter({ $0.content?.contains(content) == true })
let intentNotes = IntentNote.makeIntentNotes(from: filteredNotes)
return resolve(intentNotes)
}
static func resolveIntentNote(forTag tag: IntentTag, in coreDataWrapper: ExtensionCoreDataWrapper) -> IntentNoteResolutionResult {
guard let notesForTag = coreDataWrapper.resultsController()?.notes(filteredBy: .tag(tag.displayString)) else {
return IntentNoteResolutionResult.unsupported()
}
let intentNotes = IntentNote.makeIntentNotes(from: notesForTag)
return resolve(intentNotes)
}
private static func resolve(_ intentNotes: [IntentNote]) -> IntentNoteResolutionResult {
guard intentNotes.isEmpty == false else {
return IntentNoteResolutionResult.unsupported()
}
if intentNotes.count == 1,
let intentNote = intentNotes.first {
return IntentNoteResolutionResult.success(with: intentNote)
}
return IntentNoteResolutionResult.disambiguation(with: intentNotes)
}
}
extension IntentNote {
static func allNotes(in coreDataWrapper: ExtensionCoreDataWrapper) throws -> [IntentNote] {
guard let notes = coreDataWrapper.resultsController()?.notes() else {
throw IntentsError.couldNotFetchNotes
}
return makeIntentNotes(from: notes)
}
static func makeIntentNotes(from notes: [Note]) -> [IntentNote] {
notes.map({ IntentNote(identifier: $0.simperiumKey, display: $0.title) })
}
}
``` | /content/code_sandbox/SimplenoteIntents/ResolutionResults/IntentNote+Helpers.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 529 |
```swift
//
// IntentTag+Helpers.swift
// SimplenoteIntents
//
// Created by Charlie Scheer on 5/9/24.
//
import Intents
extension IntentTag {
static func allTags(in coreDataWrapper: ExtensionCoreDataWrapper) throws -> [IntentTag] {
guard let tags = coreDataWrapper.resultsController()?.tags() else {
throw IntentsError.couldNotFetchTags
}
return tags.map({ IntentTag(identifier: $0.simperiumKey, display: $0.name ?? String()) })
}
}
``` | /content/code_sandbox/SimplenoteIntents/ResolutionResults/IntentTag+Helpers.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 121 |
```swift
import Foundation
import UniformTypeIdentifiers
public class RecoveryArchiver {
private let fileManager: FileManager
public init(fileManager: FileManager = .default) {
self.fileManager = fileManager
}
// MARK: Archive
//
public func archiveContent(_ content: String) {
guard let fileURL = url(for: UUID().uuidString) else {
return
}
guard let data = content.data(using: .utf8) else {
return
}
try? data.write(to: fileURL)
}
private func url(for identifier: String) -> URL? {
guard let recoveryDirURL = fileManager.recoveryDirectoryURL() else {
return nil
}
let formattedID = identifier.replacingOccurrences(of: "/", with: "-")
let fileName = "\(Constants.recoveredContent)-\(formattedID)"
return recoveryDirURL.appendingPathComponent(fileName, conformingTo: UTType.json)
}
}
private struct Constants {
static let recoveredContent = "recoveredContent"
}
``` | /content/code_sandbox/SimplenoteIntents/Tools/RecoveryArchiver.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 220 |
```swift
import Foundation
struct Notice {
let message: String
let action: NoticeAction?
var hasAction: Bool {
return action != nil
}
}
extension Notice: Equatable {
static func == (lhs: Notice, rhs: Notice) -> Bool {
return lhs.message == rhs.message
}
}
``` | /content/code_sandbox/Simplenote/Notice.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 69 |
```swift
import UIKit
// MARK: - UISlider + Simplenote
//
extension UISlider {
/// Rect for thumb
///
var thumbRect: CGRect {
return thumbRect(forBounds: bounds,
trackRect: trackRect(forBounds: bounds),
value: value)
}
}
``` | /content/code_sandbox/Simplenote/UISlider+Simplenote.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 63 |
```swift
import Foundation
import Simperium
// MARK: - SPManagedObject extension
//
extension SPManagedObject {
/// Version as an Int
///
@objc
var versionInt: Int {
guard let versionStr = version(), let version = Int(versionStr) else {
return 1
}
return version
}
}
``` | /content/code_sandbox/Simplenote/SPManagedObject+Version.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 73 |
```swift
//
// StoreProduct.swift
// Simplenote
//
// Created by Jorge Leandro Perez on 10/26/22.
//
import Foundation
// MARK: - StoreProduct
//
enum StoreProduct: String, CaseIterable {
case sustainerMonthly
case sustainerYearly
var identifier: String {
switch self {
case .sustainerYearly:
return "com.codality.NotationalFlow.sustainer200"
case .sustainerMonthly:
return "com.codality.NotationalFlow.sustainer20"
}
}
}
extension StoreProduct {
static var allIdentifiers: [String] {
StoreProduct.allCases.map { product in
product.identifier
}
}
static func findStoreProduct(identifier: String) -> StoreProduct? {
StoreProduct.allCases.first { storeProduct in
storeProduct.identifier == identifier
}
}
}
``` | /content/code_sandbox/Simplenote/StoreProduct.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 196 |
```swift
import Foundation
extension URLComponents {
static func simplenoteURLComponents(with host: String? = nil) -> URLComponents? {
var components = URLComponents(string: .simplenotePath())
components?.host = host
return components
}
}
``` | /content/code_sandbox/Simplenote/URLComponents.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 58 |
```swift
import Foundation
extension Date {
func increased(byHours hours: Int) -> Date? {
var components = DateComponents()
components.hour = hours
return Calendar.current.date(byAdding: components, to: self)
}
func increased(byDays days: Int) -> Date? {
var components = DateComponents()
components.day = days
return Calendar.current.date(byAdding: components, to: self)
}
}
``` | /content/code_sandbox/Simplenote/Date+Simplenote.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 92 |
```swift
import Foundation
import SimplenoteFoundation
// MARK: - TagListViewController
//
final class TagListViewController: UIViewController {
@IBOutlet private weak var tableView: UITableView!
@IBOutlet private weak var rightBorderView: UIView!
@IBOutlet private weak var rightBorderWidthConstraint: NSLayoutConstraint!
private lazy var tagsHeaderView: SPTagHeaderView = SPTagHeaderView.instantiateFromNib()
private lazy var resultsController: ResultsController<Tag> = {
let mainContext = SPAppDelegate.shared().managedObjectContext
return ResultsController(viewContext: mainContext,
sortedBy: sortDescriptors)
}()
private var renameTag: Tag?
private var bannerView: BannerView?
private var isActiveSustainer: Bool {
SPAppDelegate.shared().simperium.preferencesObject().isActiveSubscriber
}
override var shouldAutorotate: Bool {
return false
}
deinit {
NotificationCenter.default.removeObserver(self)
}
override func viewDidLoad() {
super.viewDidLoad()
configureTableView()
configureTableHeaderView()
configureRightBorderView()
configureMenuController()
startListeningToNotifications()
refreshStyle()
performFetch()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
startListeningToKeyboardNotifications()
reloadTableView()
startListeningForChanges()
becomeFirstResponder()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
setEditing(false)
stopListeningToKeyboardNotifications()
stopListeningForChanges()
resignFirstResponder()
}
}
// MARK: - Configuration
//
private extension TagListViewController {
func configureView() {
view.backgroundColor = .simplenoteBackgroundColor
}
func configureTableView() {
tableView.register(TagListViewCell.loadNib(), forCellReuseIdentifier: TagListViewCell.reuseIdentifier)
tableView.register(Value1TableViewCell.self, forCellReuseIdentifier: Value1TableViewCell.reuseIdentifier)
tableView.separatorInsetReference = .fromAutomaticInsets
tableView.automaticallyAdjustsScrollIndicatorInsets = false
}
func configureTableHeaderView() {
tagsHeaderView.titleLabel.text = Localization.tags
tagsHeaderView.titleLabel.font = .preferredFont(for: .title2, weight: .bold)
let actionButton = tagsHeaderView.actionButton
actionButton?.setTitle(Localization.edit, for: .normal)
actionButton?.addTarget(self, action: #selector(editTagsTap), for: .touchUpInside)
}
func configureRightBorderView() {
rightBorderWidthConstraint.constant = UIScreen.main.pointToPixelRatio
}
func configureMenuController() {
let renameSelector = sel_registerName("rename:")
let renameItem = UIMenuItem(title: Localization.rename, action: renameSelector)
UIMenuController.shared.menuItems = [renameItem]
UIMenuController.shared.update()
}
}
// MARK: - Notifications
//
private extension TagListViewController {
func startListeningToNotifications() {
let nc = NotificationCenter.default
nc.addObserver(self, selector: #selector(menuDidChangeVisibility), name: UIMenuController.didShowMenuNotification, object: nil)
nc.addObserver(self, selector: #selector(menuDidChangeVisibility), name: UIMenuController.didHideMenuNotification, object: nil)
nc.addObserver(self, selector: #selector(tagsSortOrderWasUpdated), name: NSNotification.Name.SPAlphabeticalTagSortPreferenceChanged, object: nil)
nc.addObserver(self, selector: #selector(themeDidChange), name: NSNotification.Name.SPSimplenoteThemeChanged, object: nil)
}
func startListeningToKeyboardNotifications() {
let nc = NotificationCenter.default
nc.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
nc.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
}
func stopListeningToKeyboardNotifications() {
let nc = NotificationCenter.default
nc.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil)
nc.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)
}
}
// MARK: - Notifications
//
private extension TagListViewController {
@objc
func themeDidChange() {
refreshStyle()
}
@objc
func menuDidChangeVisibility() {
tableView.allowsSelection = !UIMenuController.shared.isMenuVisible
}
@objc
func tagsSortOrderWasUpdated() {
refreshSortDescriptorsAndPerformFetch()
}
}
// MARK: - Style
//
private extension TagListViewController {
func refreshStyle() {
rightBorderView.backgroundColor = .simplenoteDividerColor
tagsHeaderView.refreshStyle()
tableView.applySimplenotePlainStyle()
reloadTableView()
}
}
// MARK: - Button actions
//
private extension TagListViewController {
@objc
func editTagsTap() {
let newState = !isEditing
if newState {
SPTracker.trackTagEditorAccessed()
}
setEditing(newState)
}
}
// MARK: - Helper Methods
//
private extension TagListViewController {
func cell(for tag: Tag) -> TagListViewCell? {
guard let indexPath = indexPath(for: tag) else {
return nil
}
return tableView.cellForRow(at: indexPath) as? TagListViewCell
}
func indexPath(for tag: Tag) -> IndexPath? {
guard let indexPath = resultsController.indexPath(forObject: tag) else {
return nil
}
return IndexPath(row: indexPath.row, section: Section.tags.rawValue)
}
func tag(at indexPath: IndexPath) -> Tag? {
guard indexPath.row < numberOfTags
&& Section(rawValue: indexPath.section) == .tags else {
return nil
}
// Our FRC has just one section!
let indexPath = IndexPath(row: indexPath.row, section: 0)
return resultsController.object(at: indexPath)
}
var numberOfTags: Int {
return resultsController.numberOfObjects
}
}
// MARK: - Table
//
extension TagListViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if Section(rawValue: section) == .tags {
return UITableView.automaticDimension
}
return CGFloat.leastNormalMagnitude
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if Section(rawValue: section) == .tags {
return tagsHeaderView
}
return nil
}
func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
let isTagRow = Section(rawValue: indexPath.section) == .tags
let isSortEnabled = UserDefaults.standard.bool(forKey: SPAlphabeticalTagSortPref)
return isTagRow && !isSortEnabled
}
func numberOfSections(in tableView: UITableView) -> Int {
return numberOfTags == 0 ? 1 : Section.allCases.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let section = Section(rawValue: section) else {
return 0
}
switch section {
case .system:
return SystemRow.allCases.count
case .tags:
return numberOfTags
case .bottom:
return 1
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let section = Section(rawValue: indexPath.section) else {
return UITableViewCell()
}
switch section {
case .system:
let cell = tableView.dequeueReusableCell(ofType: Value1TableViewCell.self, for: indexPath)
configureSystemCell(cell, at: indexPath)
return cell
case .tags:
let cell = tableView.dequeueReusableCell(ofType: TagListViewCell.self, for: indexPath)
configureTagCell(cell, at: indexPath)
return cell
case .bottom:
let cell = tableView.dequeueReusableCell(ofType: Value1TableViewCell.self, for: indexPath)
configureBottomCell(cell, at: indexPath)
return cell
}
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cell.adjustSeparatorWidth(width: .full)
}
func tableView(_ tableView: UITableView, shouldShowMenuForRowAt indexPath: IndexPath) -> Bool {
let isTagRow = Section(rawValue: indexPath.section) == .tags
if isTagRow {
SPTracker.trackTagCellPressed()
}
return isTagRow
}
func tableView(_ tableView: UITableView, canPerformAction action: Selector, forRowAt indexPath: IndexPath, withSender sender: Any?) -> Bool {
return true
}
func tableView(_ tableView: UITableView, performAction action: Selector, forRowAt indexPath: IndexPath, withSender sender: Any?) {
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
didSelectRow(at: indexPath, isTraversing: false)
}
func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
guard Section(rawValue: sourceIndexPath.section) == .tags
&& Section(rawValue: destinationIndexPath.section) == .tags else {
return
}
stopListeningForChanges()
SPObjectManager.shared().moveTag(from: sourceIndexPath.row,
to: destinationIndexPath.row)
startListeningForChanges()
}
func tableView(_ tableView: UITableView, targetIndexPathForMoveFromRowAt sourceIndexPath: IndexPath, toProposedIndexPath proposedDestinationIndexPath: IndexPath) -> IndexPath {
guard Section(rawValue: sourceIndexPath.section) == .tags
&& Section(rawValue: proposedDestinationIndexPath.section) == .tags else {
return sourceIndexPath
}
return proposedDestinationIndexPath
}
func tableView(_ tableView: UITableView, shouldIndentWhileEditingRowAt indexPath: IndexPath) -> Bool {
return false
}
func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
return .none
}
func reloadTableView() {
tableView.reloadData()
updateCurrentSelection()
}
}
// MARK: - Cell Setup
//
private extension TagListViewController {
func configureSystemCell(_ cell: Value1TableViewCell, at indexPath: IndexPath) {
guard let row = SystemRow(rawValue: indexPath.row) else {
return
}
cell.hasClearBackground = true
cell.imageTintColor = .simplenoteTintColor
switch row {
case .allNotes:
cell.title = Localization.allNotes
cell.imageView?.image = .image(name: .allNotes)
cell.accessibilityIdentifier = "all-notes"
case .trash:
cell.title = Localization.trash
cell.imageView?.image = .image(name: .trash)
cell.accessibilityIdentifier = nil
case .settings:
cell.title = Localization.settings
cell.imageView?.image = .image(name: .settings)
cell.accessibilityIdentifier = "settings"
}
}
func configureTagCell(_ cell: TagListViewCell, at indexPath: IndexPath) {
let tagName = tag(at: indexPath)?.name
cell.textField.text = tagName
cell.delegate = self
}
func configureBottomCell(_ cell: Value1TableViewCell, at indexPath: IndexPath) {
cell.title = Localization.untaggedNotes
cell.imageView?.image = .image(name: .untagged)
cell.accessibilityIdentifier = nil
cell.hasClearBackground = true
cell.imageTintColor = .simplenoteTintColor
}
}
// MARK: - Selection
//
private extension TagListViewController {
func updateCurrentSelection() {
tableView.selectRow(at: currentSelection, animated: false, scrollPosition: .none)
}
var currentSelection: IndexPath? {
let filter = NotesListFilter(selectedTag: SPAppDelegate.shared().selectedTag)
switch filter {
case .everything:
return IndexPath(row: SystemRow.allNotes.rawValue,
section: Section.system.rawValue)
case .deleted:
return IndexPath(row: SystemRow.trash.rawValue,
section: Section.system.rawValue)
case .untagged:
return IndexPath(row: 0,
section: Section.bottom.rawValue)
case .tag(let tagName):
guard let index = resultsController.fetchedObjects.firstIndex(where: {
$0.name == tagName
}) else {
return nil
}
return IndexPath(row: index,
section: Section.tags.rawValue)
}
}
}
// MARK: - Row Press Handlers
//
private extension TagListViewController {
func didSelectRow(at indexPath: IndexPath, isTraversing: Bool) {
guard let section = Section(rawValue: indexPath.section) else {
return
}
switch section {
case .system:
didSelectSystemRow(at: indexPath, isTraversing: isTraversing)
case .tags:
didSelectTag(at: indexPath, isTraversing: isTraversing)
case .bottom:
didSelectBottomRow(at: indexPath, isTraversing: isTraversing)
}
}
func didSelectSystemRow(at indexPath: IndexPath, isTraversing: Bool) {
guard let row = SystemRow(rawValue: indexPath.row) else {
return
}
if !isTraversing {
setEditing(false)
}
switch row {
case .allNotes:
openNoteListForTagName(nil, isTraversing: isTraversing)
case .trash:
SPTracker.trackTrashViewed()
openNoteListForTagName(kSimplenoteTrashKey, isTraversing: isTraversing)
case .settings:
if isTraversing {
return
}
updateCurrentSelection()
SPAppDelegate.shared().presentSettingsViewController()
}
}
func didSelectTag(at indexPath: IndexPath, isTraversing: Bool) {
guard let tag = tag(at: indexPath) else {
return
}
if isEditing && !isTraversing {
SPTracker.trackTagRowRenamed()
renameTag(tag)
} else {
SPTracker.trackListTagViewed()
openNoteListForTagName(tag.name, isTraversing: isTraversing)
}
}
func didSelectBottomRow(at indexPath: IndexPath, isTraversing: Bool) {
if !isTraversing {
setEditing(false)
}
SPTracker.trackListUntaggedViewed()
openNoteListForTagName(kSimplenoteUntaggedKey, isTraversing: isTraversing)
}
}
// MARK: - TagListViewCellDelegate
//
extension TagListViewController: TagListViewCellDelegate {
func tagListViewCellShouldRenameTag(_ cell: TagListViewCell) {
SPTracker.trackTagMenuRenamed()
guard let indexPath = tableView.indexPath(for: cell),
let tag = tag(at: indexPath) else {
return
}
renameTag(tag)
}
func tagListViewCellShouldDeleteTag(_ cell: TagListViewCell, source: TagListViewCellDeletionSource) {
guard let indexPath = tableView.indexPath(for: cell), let tag = tag(at: indexPath) else {
return
}
let alertController = UIAlertController(title: Localization.TagDeletionConfirmation.title(with: tag.name ?? ""),
message: nil,
preferredStyle: .actionSheet)
alertController.addDestructiveActionWithTitle(Localization.TagDeletionConfirmation.confirmationButton) { (_) in
guard self.verifyTagIsAtIndexPath(tag, at: indexPath) else {
self.present(UIAlertController.dismissableAlert(
title: Localization.tagDeleteFailedTitle,
message: Localization.tagDeleteFailedMessage), animated: true)
return
}
switch source {
case .accessory:
SPTracker.trackTagRowDeleted()
case .menu:
SPTracker.trackTagMenuDeleted()
}
self.removeTag(at: indexPath)
}
alertController.addCancelActionWithTitle(Localization.TagDeletionConfirmation.cancellationButton)
alertController.popoverPresentationController?.sourceRect = cell.bounds
alertController.popoverPresentationController?.sourceView = cell
alertController.popoverPresentationController?.permittedArrowDirections = .any
present(alertController, animated: true, completion: nil)
}
private func verifyTagIsAtIndexPath(_ tagToRemove: Tag, at indexPath: IndexPath) -> Bool {
// REF: path_to_url
// If you initiate deleting a tag and the tag is deleted before you confirm then another tag is deleted
// This method confirms the selected tag is the same as the tag at index path before removing.
guard let tagAtIndexPath = tag(at: indexPath) else {
return false
}
return tagToRemove.simperiumKey == tagAtIndexPath.simperiumKey
}
}
// MARK: - Helper Methods
//
private extension TagListViewController {
func setEditing(_ editing: Bool) {
// Note: Neither super.setEditing nor tableView.setEditing will resign the first responder.
if !editing {
view.endEditing(true)
}
super.setEditing(editing, animated: true)
tableView.setEditing(editing, animated: true)
refreshEditTagsButton(isEditing: editing)
updateCurrentSelection()
}
func refreshEditTagsButton(isEditing: Bool) {
let title = isEditing ? Localization.done : Localization.edit
tagsHeaderView.actionButton.setTitle(title, for: .normal)
}
// This method is for refreshing the size of the sustainer view. We are retiring sustainer so this is no longer needed
// but we may want to use the banner again in the future, so leaving this here in case. Method is not being called anywhere
func refreshTableHeaderView() {
guard let bannerView else {
return
}
if isActiveSustainer {
tableView.tableHeaderView = nil
return
}
bannerView.preferredWidth = tableView.frame.width - view.safeAreaInsets.left
bannerView.adjustSizeForCompressedLayout()
tableView.tableHeaderView = bannerView
}
func openNoteListForTagName(_ tagName: String?, isTraversing: Bool) {
let appDelegate = SPAppDelegate.shared()
appDelegate.selectedTag = tagName
if !isTraversing {
appDelegate.sidebarViewController.hideSidebar(withAnimation: true)
}
}
}
// MARK: - UIGestureRecognizerDelegate
//
extension TagListViewController: UIGestureRecognizerDelegate {
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
}
// MARK: - Tag Actions
//
private extension TagListViewController {
func removeTag(at indexPath: IndexPath) {
guard let tag = tag(at: indexPath) else {
return
}
let appDelegate = SPAppDelegate.shared()
if appDelegate.selectedTag == tag.name {
appDelegate.selectedTag = nil
}
SPObjectManager.shared().removeTag(tag)
}
func renameTag(_ tag: Tag) {
if let renameTag = renameTag {
cell(for: renameTag)?.textField.endEditing(true)
}
renameTag = tag
guard let tagCell = cell(for: tag) else {
return
}
tagCell.textField.isEnabled = true
tagCell.textField.delegate = self
tagCell.textField.becomeFirstResponder()
}
}
// MARK: - UITextFieldDelegate
//
extension TagListViewController: UITextFieldDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: 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: string)
switch result {
case .valid:
return true
case .endingWithDisallowedCharacter(let text):
textField.text = text
textField.endEditing(true)
return false
case .invalid:
return false
}
}
func textFieldDidEndEditing(_ textField: UITextField) {
guard let renameTag = renameTag else {
return
}
self.renameTag = nil
if isEditing {
updateCurrentSelection()
}
textField.isEnabled = false
textField.delegate = nil
let originalTagName = renameTag.name
let newTagName = textField.text ?? ""
// see if tag already exists, if not rename. If it does, revert back to original name
let shouldRenameTag = !SPObjectManager.shared().tagExists(newTagName)
if shouldRenameTag {
SPObjectManager.shared().editTag(renameTag, title: newTagName)
let appDelegate = SPAppDelegate.shared()
if appDelegate.selectedTag == originalTagName {
appDelegate.selectedTag = newTagName
}
} else {
textField.text = originalTagName
}
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
// MARK: - Results Controller
//
private extension TagListViewController {
var sortDescriptors: [NSSortDescriptor] {
let isAlphaSort = UserDefaults.standard.bool(forKey: SPAlphabeticalTagSortPref)
let sortDescriptor: NSSortDescriptor
if isAlphaSort {
sortDescriptor = NSSortDescriptor(
key: "name",
ascending: true,
selector: #selector(NSString.localizedCaseInsensitiveCompare(_:)))
} else {
sortDescriptor = NSSortDescriptor(key: "index", ascending: true)
}
return [sortDescriptor]
}
func performFetch() {
try? resultsController.performFetch()
reloadTableView()
}
func refreshSortDescriptorsAndPerformFetch() {
resultsController.sortDescriptors = sortDescriptors
performFetch()
}
func startListeningForChanges() {
resultsController.onDidChangeContent = { [weak self] (sectionsChangeset, objectsChangeset) in
guard let self = self else {
return
}
guard self.tableView.window != nil else {
return
}
// Reload if number of sections is different
// Results controller supports only tags section. We show/hide tags section based on the number of tags
guard self.tableView.numberOfSections == self.numberOfSections(in: self.tableView) else {
self.setEditing(false)
self.reloadTableView()
return
}
// If the change includes deleting the tag that is currently being edited
// remove the reselect rename tag, disable editing and reload tableView
if let renameTag = self.renameTag, !self.resultsController.fetchedObjects.contains(renameTag) {
self.renameTag = nil
self.setEditing(false)
self.reloadTableView()
return
}
self.reloadTable(with: sectionsChangeset.transposed(toSection: Section.tags.rawValue),
objectsChangeset: objectsChangeset.transposed(toSection: Section.tags.rawValue))
}
}
func stopListeningForChanges() {
resultsController.onDidChangeContent = nil
}
func reloadTable(with sectionsChangeset: ResultsSectionsChangeset, objectsChangeset: ResultsObjectsChangeset) {
self.tableView.performBatchUpdates({
// Disable animation for row updates
let animations = ResultsTableAnimations(delete: .fade, insert: .fade, move: .fade, update: .none)
self.tableView.performChanges(sectionsChangeset: sectionsChangeset,
objectsChangeset: objectsChangeset,
animations: animations)
}, completion: nil)
updateCurrentSelection()
}
}
// MARK: - KeyboardNotifications
//
private extension TagListViewController {
@objc
func keyboardWillShow(_ notification: NSNotification) {
let keyboardFrame = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue ?? .zero
let duration = (notification.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue ?? 0
var contentInsets = tableView.contentInset
var scrollInsets = tableView.verticalScrollIndicatorInsets
let keyboardHeight = min(keyboardFrame.size.height, keyboardFrame.size.width)
contentInsets.bottom = keyboardHeight
scrollInsets.bottom = keyboardHeight
UIView.animate(withDuration: TimeInterval(duration), animations: {
self.tableView.contentInset = contentInsets
self.tableView.verticalScrollIndicatorInsets = scrollInsets
})
}
@objc
func keyboardWillHide(_ notification: NSNotification) {
var contentInsets = tableView.contentInset
contentInsets.bottom = view.safeAreaInsets.bottom
let duration = (notification.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue ?? 0
UIView.animate(withDuration: TimeInterval(duration), animations: {
self.tableView.contentInset = contentInsets
self.tableView.scrollIndicatorInsets = .zero
})
}
}
// MARK: - Keyboard Support
//
extension TagListViewController {
override var canBecomeFirstResponder: Bool {
return true
}
override var keyCommands: [UIKeyCommand]? {
guard isFirstResponder else {
return nil
}
var commands = [
UIKeyCommand(input: UIKeyCommand.inputTrailingArrow, modifierFlags: [], action: #selector(keyboardHideSidebar))
]
commands.append(contentsOf: tableCommands)
return commands
}
@objc
private func keyboardHideSidebar() {
let appDelegate = SPAppDelegate.shared()
appDelegate.sidebarViewController.hideSidebar(withAnimation: true)
}
}
// MARK: - Keyboard support (List)
//
private extension TagListViewController {
var tableCommands: [UIKeyCommand] {
[
UIKeyCommand(input: UIKeyCommand.inputUpArrow, modifierFlags: [], action: #selector(keyboardUp)),
UIKeyCommand(input: UIKeyCommand.inputDownArrow, modifierFlags: [], action: #selector(keyboardDown)),
UIKeyCommand(input: "\r", modifierFlags: [], action: #selector(keyboardSelect))
]
}
@objc
func keyboardUp() {
tableView?.selectPrevRow()
updateSelectionWhileTraversing()
}
@objc
func keyboardDown() {
tableView?.selectNextRow()
updateSelectionWhileTraversing()
}
@objc
func keyboardSelect() {
tableView?.executeSelection()
}
func updateSelectionWhileTraversing() {
guard let indexPath = tableView.indexPathForSelectedRow else {
return
}
// Skip for settings
if indexPath.section == Section.system.rawValue && indexPath.row == SystemRow.settings.rawValue {
return
}
didSelectRow(at: indexPath, isTraversing: true)
}
}
// MARK: - Section enum
//
private enum Section: Int, CaseIterable {
case system
case tags
case bottom
}
// MARK: - System Row enum
//
private enum SystemRow: Int, CaseIterable {
case allNotes
case trash
case settings
}
// MARK: - Constants
//
private struct Constants {
static let tagListBatchSize = 20
}
// MARK: - Localization
//
private struct Localization {
static let edit = NSLocalizedString("Edit", comment: "Edit Tags Action: Visible in the Tags List")
static let rename = NSLocalizedString("Rename", comment: "Rename a tag")
static let done = NSLocalizedString("Done", comment: "Done editing tags")
static let allNotes = NSLocalizedString("All Notes", comment: "All Notes filter button")
static let trash = NSLocalizedString("Trash", comment: "Trash filter button")
static let settings = NSLocalizedString("Settings", comment: "Settings button")
static let tags = NSLocalizedString("Tags", comment: "Tags List Header")
static let untaggedNotes = NSLocalizedString("Untagged Notes", comment: "Allows selecting notes with no tags")
static let tagDeleteFailedTitle = NSLocalizedString("Could not delete tag", comment: "Notifies user tag delete failed")
static let tagDeleteFailedMessage = NSLocalizedString("Please try again", comment: "Encourages trying delete again")
struct TagDeletionConfirmation {
static func title(with tagName: String) -> String {
let template = NSLocalizedString("Are you sure you want to delete \"%1$@\"?", comment: "Title of deletion confirmation message for a tag. Parameters: %1$@ - tag name")
return String(format: template, tagName)
}
static let confirmationButton = NSLocalizedString("Delete Tag", comment: "Confirmation button of deletion confirmation message for a tag.")
static let cancellationButton = NSLocalizedString("Cancel", comment: "Cancellation button of deletion confirmation message for a tag.")
}
}
``` | /content/code_sandbox/Simplenote/TagListViewController.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 6,017 |
```swift
import Foundation
// MARK: - SPPinLockManager
//
class SPPinLockManager: NSObject {
@objc
static let shared = SPPinLockManager()
private let biometricAuthentication: BiometricAuthentication
init(biometricAuthentication: BiometricAuthentication = BiometricAuthentication()) {
self.biometricAuthentication = biometricAuthentication
}
/// Should we bypass pin lock due to timeout settings?
///
var shouldBypassPinLock: Bool {
guard let lastUsedSeconds = Int(KeychainManager.timestamp ?? "0"),
lastUsedSeconds > 0 else {
return false
}
let maxTimeoutSeconds = pinLockTimeoutSeconds
// User has timeout set to 'Off' setting (0)
if maxTimeoutSeconds == 0 {
return false
}
var ts = timespec.init()
clock_gettime(CLOCK_MONOTONIC_RAW, &ts)
let nowSeconds = max(0, Int(ts.tv_sec)) // The running clock time of the device
// User may have recently rebooted their device, so we'll enforce lock screen
if lastUsedSeconds > nowSeconds {
return false
}
let intervalSinceLastUsed = nowSeconds - lastUsedSeconds
return intervalSinceLastUsed < maxTimeoutSeconds
}
private var pinLockTimeoutSeconds: Int {
let timeoutPref = UserDefaults.standard.integer(forKey: kPinTimeoutPreferencesKey)
let timeoutValues = [0, 15, 30, 60, 120, 180, 240, 300]
if timeoutPref > timeoutValues.count {
return 0
}
return timeoutValues[timeoutPref]
}
/// Store last time the app was used
///
@objc
func storeLastUsedTime() {
guard isEnabled else {
return
}
var ts = timespec()
clock_gettime(CLOCK_MONOTONIC_RAW, &ts)
let nowTime = String(format: "%ld", ts.tv_sec)
KeychainManager.timestamp = nowTime
}
/// Is pin enabled
///
@objc
var isEnabled: Bool {
pin?.isEmpty == false
}
/// Set pin
///
func setPin(_ pin: String) {
self.pin = pin
}
/// Remove pin
///
@objc
func removePin() {
pin = nil
shouldUseBiometry = false
}
/// Check if provided pin is valid
///
func validatePin(_ pin: String) -> Bool {
isEnabled && pin == self.pin
}
@objc
private var pin: String? {
get {
KeychainManager.pinlock
}
set {
KeychainManager.pinlock = newValue
}
}
// MARK: - Biometry
/// Should the app try to use biometry?
///
@objc
var shouldUseBiometry: Bool {
get {
Options.shared.useBiometryInsteadOfPin
}
set {
Options.shared.useBiometryInsteadOfPin = newValue
}
}
var availableBiometry: BiometricAuthentication.Biometry? {
biometricAuthentication.availableBiometry
}
func evaluateBiometry(completion: @escaping (_ success: Bool) -> Void) {
guard shouldUseBiometry else {
completion(false)
return
}
biometricAuthentication.evaluate(completion: completion)
}
}
``` | /content/code_sandbox/Simplenote/SPPinLockManager.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 734 |
```swift
import Foundation
// MARK: - NoteMetrics
//
struct NoteMetrics {
/// Returns the total number of characters
///
let numberOfChars: Int
/// Returns the total number of words
///
let numberOfWords: Int
/// Creation Date
///
let creationDate: Date
/// Modification Date
///
let modifiedDate: Date
/// Designed Initializer
/// - Parameter note: Note from which we should extract metrics
///
init(note: Note) {
let content = ((note.content ?? "") as NSString)
numberOfChars = content.charCount
numberOfWords = content.wordCount
creationDate = note.creationDate
modifiedDate = note.modificationDate
}
}
``` | /content/code_sandbox/Simplenote/NoteMetrics.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 157 |
```swift
import UIKit
class SpinnerViewController: UIViewController {
private var alertView = UIView()
private var activityIndicator = UIActivityIndicatorView()
init() {
super.init(nibName: nil, bundle: nil)
setupView()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setupView()
}
private func setupView() {
setupViewLayout()
setupViewAppearance()
}
private func setupViewLayout() {
alertView = UIView(frame: .zero)
activityIndicator = UIActivityIndicatorView(frame: .zero)
alertView.translatesAutoresizingMaskIntoConstraints = false
activityIndicator.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(alertView)
NSLayoutConstraint.activate([
alertView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
alertView.centerYAnchor.constraint(equalTo: view.centerYAnchor),
alertView.widthAnchor.constraint(equalToConstant: Constants.width),
alertView.heightAnchor.constraint(equalToConstant: Constants.height)
])
alertView.layer.cornerRadius = Constants.cornerRadius
alertView.addSubview(activityIndicator)
alertView.sizeToFit()
NSLayoutConstraint.activate([
activityIndicator.centerXAnchor.constraint(equalTo: alertView.centerXAnchor),
activityIndicator.centerYAnchor.constraint(equalTo: alertView.centerYAnchor),
])
}
override func viewWillAppear(_ animated: Bool) {
activityIndicator.startAnimating()
}
override func viewDidDisappear(_ animated: Bool) {
activityIndicator.stopAnimating()
}
private func setupViewAppearance() {
modalPresentationStyle = .overFullScreen
view.backgroundColor = UIColor(lightColor: .black, darkColor: .black, lightColorAlpha: 0.2, darkColorAlpha: 0.43)
alertView.backgroundColor = UIColor(lightColor: .spGray2, darkColor: .darkGray2)
activityIndicator.color = UIColor(lightColor: .black, darkColor: .spGray1)
activityIndicator.style = .large
}
}
private struct Constants {
static let width: CGFloat = 150
static let height: CGFloat = 115
static let cornerRadius: CGFloat = 15
}
``` | /content/code_sandbox/Simplenote/SpinnerViewController.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 428 |
```swift
import Foundation
import SimplenoteEndpoints
import Simperium
// MARK: - Simperium's SPUser Conformance
//
extension SPUser: UserProtocol { }
``` | /content/code_sandbox/Simplenote/SPUser+UserProtocol.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 37 |
```swift
import Foundation
// MARK: - NoteScrollPositionCache: cache scroll offset
//
final class NoteScrollPositionCache {
typealias ScrollCache = [String: CGFloat]
private var cache: ScrollCache {
didSet {
try? storage.save(object: cache)
}
}
private let storage: FileStorage<ScrollCache>
init(storage: FileStorage<ScrollCache>) {
self.storage = storage
let storedCache = try? storage.load()
cache = storedCache ?? [:]
}
/// Returns cached scroll position
///
func position(for key: String) -> CGFloat? {
return cache[key]
}
/// Stores scroll position
///
func store(position: CGFloat, for key: String) {
cache[key] = position
}
/// Cleanup
///
func cleanup(keeping keys: [String]) {
cache = cache.filter({ keys.contains($0.key) })
}
}
``` | /content/code_sandbox/Simplenote/NoteScrollPositionCache.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 198 |
```swift
import UIKit
// MARK: - SPCardDismissalReason: reason why card view controller was dismissed
//
enum SPCardDismissalReason {
/// Swipe down
///
case swipe
/// Tap outside of the card
///
case outsideTap
}
// MARK: - SPCardPresentationControllerDelegate
//
protocol SPCardPresentationControllerDelegate: AnyObject {
func cardDidDismiss(_ viewController: UIViewController, reason: SPCardDismissalReason)
}
// MARK: - SPCardPresentationController: Manages presentation and swipe to dismiss
//
final class SPCardPresentationController: UIPresentationController {
private lazy var cardView = SPCardView()
private lazy var dimmingView: UIView = {
let view = UIView()
view.backgroundColor = UIColor.simplenoteDimmingColor
return view
}()
private lazy var tapGestureRecognizer = UITapGestureRecognizer(target: self,
action: #selector(handleTap(_:)))
private lazy var panGestureRecognizer: UIPanGestureRecognizer = {
let gestureRecognizer = UIPanGestureRecognizer(target: self,
action: #selector(handlePan(_:)))
gestureRecognizer.delegate = self
return gestureRecognizer
}()
private var compactWidthLayoutConstraints: [NSLayoutConstraint] = []
private var regularWidthLayoutConstraints: [NSLayoutConstraint] = []
private var regularHeightLayoutConstraints: [NSLayoutConstraint] = []
/// Transition interactor is set only during swipe to dismiss
///
private(set) var transitionInteractor: UIPercentDrivenInteractiveTransition?
/// Delegate for presentation (and dismissal) related events
///
weak var presentationDelegate: SPCardPresentationControllerDelegate?
/// Returns our own card wrapper view instead of default view controller view
///
override var presentedView: UIView? {
return cardView
}
// MARK: - Presentation
override func presentationTransitionWillBegin() {
super.presentationTransitionWillBegin()
setupGestureRecognizers()
addDimmingView()
addCardView()
cardView.addContentView(presentedViewController.view)
fadeInDimmingView()
}
override func presentationTransitionDidEnd(_ completed: Bool) {
super.presentationTransitionDidEnd(completed)
if !completed {
removeViews()
removeGestureRecognizers()
}
}
// MARK: - Dismissal
override func dismissalTransitionWillBegin() {
super.dismissalTransitionWillBegin()
fadeOutDimmingView()
}
override func dismissalTransitionDidEnd(_ completed: Bool) {
super.dismissalTransitionDidEnd(completed)
if completed {
removeViews()
removeGestureRecognizers()
}
}
}
// MARK: - Handle changes in trait collection
//
extension SPCardPresentationController {
override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {
super.willTransition(to: newCollection, with: coordinator)
coordinator.animate(alongsideTransition: { _ in
self.updateConstraints(for: newCollection)
}, completion: nil)
}
private func updateConstraints(for collection: UITraitCollection) {
NSLayoutConstraint.deactivate(compactWidthLayoutConstraints + regularWidthLayoutConstraints + regularHeightLayoutConstraints)
let newWidthConstraints = collection.horizontalSizeClass == .regular ? regularWidthLayoutConstraints : compactWidthLayoutConstraints
NSLayoutConstraint.activate(newWidthConstraints)
if collection.verticalSizeClass == .regular {
NSLayoutConstraint.activate(regularHeightLayoutConstraints)
}
}
}
// MARK: - Views
//
private extension SPCardPresentationController {
func addDimmingView() {
containerView?.addFillingSubview(dimmingView)
}
func addCardView() {
guard let containerView = containerView else {
return
}
cardView.translatesAutoresizingMaskIntoConstraints = false
containerView.addSubview(cardView)
compactWidthLayoutConstraints = [
cardView.leadingAnchor.constraint(equalTo: containerView.safeAreaLayoutGuide.leadingAnchor),
cardView.trailingAnchor.constraint(equalTo: containerView.safeAreaLayoutGuide.trailingAnchor),
]
regularWidthLayoutConstraints = [
cardView.leadingAnchor.constraint(equalTo: containerView.readableContentGuide.leadingAnchor),
cardView.trailingAnchor.constraint(equalTo: containerView.readableContentGuide.trailingAnchor),
]
regularHeightLayoutConstraints = [
cardView.topAnchor.constraint(greaterThanOrEqualTo: containerView.centerYAnchor),
]
let heightConstraint = cardView.heightAnchor.constraint(equalToConstant: 0)
heightConstraint.priority = .fittingSizeLevel
NSLayoutConstraint.activate([
cardView.bottomAnchor.constraint(equalTo: containerView.bottomAnchor),
cardView.topAnchor.constraint(greaterThanOrEqualTo: containerView.safeAreaLayoutGuide.topAnchor, constant: Constants.cardMinTopMargin),
heightConstraint
])
updateConstraints(for: presentedViewController.traitCollection)
}
func removeViews() {
dimmingView.removeFromSuperview()
cardView.removeFromSuperview()
}
func setupGestureRecognizers() {
dimmingView.addGestureRecognizer(tapGestureRecognizer)
containerView?.addGestureRecognizer(panGestureRecognizer)
}
func removeGestureRecognizers() {
dimmingView.removeGestureRecognizer(tapGestureRecognizer)
containerView?.removeGestureRecognizer(panGestureRecognizer)
}
func fadeInDimmingView() {
dimmingView.alpha = UIKitConstants.alpha0_0
presentingViewController.transitionCoordinator?.animate(alongsideTransition: { _ in
self.dimmingView.alpha = UIKitConstants.alpha1_0
}, completion: nil)
}
func fadeOutDimmingView() {
presentingViewController.transitionCoordinator?.animate(alongsideTransition: { _ in
self.dimmingView.alpha = UIKitConstants.alpha0_0
}, completion: nil)
}
}
// MARK: - Gesture Recognizer Delegate
//
extension SPCardPresentationController: UIGestureRecognizerDelegate {
func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
guard gestureRecognizer == panGestureRecognizer,
let viewController = presentedViewController as? SPCardConfigurable else {
return true
}
let location = gestureRecognizer.location(in: cardView)
return viewController.shouldBeginSwipeToDismiss(from: location)
}
}
// MARK: - Swipe to dismiss
//
private extension SPCardPresentationController {
@objc func handlePan(_ gestureRecognizer: UIPanGestureRecognizer) {
guard let gestureView = gestureRecognizer.view else {
return
}
let verticalTranslation = gestureRecognizer.translation(in: gestureView).y
let cardViewHeight = cardView.bounds.height
let percentComplete = max(min(verticalTranslation / cardViewHeight, 1.0), 0.0)
switch gestureRecognizer.state {
case .began:
beginSwipeToDismiss(percentComplete)
case .changed:
updateSwipeToDismiss(percentComplete)
case .ended:
let velocity = gestureRecognizer.velocity(in: gestureView).y
finishOrCancelSwipeToDismiss(percentComplete, velocity: velocity)
default:
cancelSwipeToDismiss()
}
}
func beginSwipeToDismiss(_ percentComplete: CGFloat) {
transitionInteractor = UIPercentDrivenInteractiveTransition()
presentedViewController.dismiss(animated: true, completion: nil)
updateSwipeToDismiss(percentComplete)
}
func updateSwipeToDismiss(_ percentComplete: CGFloat) {
if percentComplete >= 1.0 {
finishSwipeToDismiss()
} else {
transitionInteractor?.update(percentComplete)
}
}
func finishOrCancelSwipeToDismiss(_ percentComplete: CGFloat, velocity: CGFloat) {
let isMovingDown = velocity >= 0
if isMovingDown &&
(percentComplete > Constants.dismissalPercentThreshold || velocity > Constants.dismissalVelocityThreshold) {
finishSwipeToDismiss()
} else {
cancelSwipeToDismiss()
}
}
func finishSwipeToDismiss() {
transitionInteractor?.finish()
cleanupTransitionInteractor()
presentationDelegate?.cardDidDismiss(presentedViewController, reason: .swipe)
}
func cancelSwipeToDismiss() {
transitionInteractor?.cancel()
cleanupTransitionInteractor()
}
func cleanupTransitionInteractor() {
transitionInteractor = nil
}
}
// MARK: - Tap to dismiss
//
private extension SPCardPresentationController {
@objc func handleTap(_ gestureRecognizer: UITapGestureRecognizer) {
let locationInCardView = gestureRecognizer.location(in: cardView)
// Ignore taps inside card view
if cardView.bounds.contains(locationInCardView) {
return
}
presentedViewController.dismiss(animated: true, completion: nil)
presentationDelegate?.cardDidDismiss(presentedViewController, reason: .outsideTap)
}
}
// MARK: - Constants
//
private struct Constants {
static let dismissalPercentThreshold = CGFloat(0.3)
static let dismissalVelocityThreshold = CGFloat(1600)
static let cardMinTopMargin = CGFloat(10.0)
}
``` | /content/code_sandbox/Simplenote/SPCardPresentationController.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 1,837 |
```objective-c
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
#import "Preferences.h"
#import "Simplenote-Swift.h"
@implementation Preferences
@dynamic ghostData;
@dynamic simperiumKey;
@dynamic recent_searches;
@dynamic analytics_enabled;
@dynamic subscription_date;
@dynamic subscription_level;
@dynamic subscription_platform;
@dynamic was_sustainer;
- (void) didChangeValueForKey:(NSString *)key
{
NSString *analyticsKey = NSStringFromSelector(@selector((analytics_enabled)));
if ([key isEqualToString:analyticsKey]) {
[CrashLogging cacheOptOutSetting: !self.analytics_enabled.boolValue];
}
NSString *subscriptionKey = NSStringFromSelector(@selector((subscription_level)));
if ([key isEqualToString:subscriptionKey]) {
[[NSNotificationCenter defaultCenter] postNotificationName:SPSubscriptionStatusDidChangeNotification object:nil];
}
[super didChangeValueForKey:key];
}
@end
``` | /content/code_sandbox/Simplenote/Preferences.m | objective-c | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 185 |
```swift
import Foundation
extension NSTextStorage {
@objc(applyBackgroundColor:toRanges:)
func applyBackgroundColor(_ color: UIColor?, toRanges wordRanges: [NSValue]?) {
guard let color = color, let wordRanges = wordRanges else {
return
}
beginEditing()
let maxLength = (string as NSString).length
for value in wordRanges {
let range = value.rangeValue
if NSMaxRange(range) > maxLength {
continue
}
addAttribute(.backgroundColor, value: color, range: range)
}
endEditing()
}
}
``` | /content/code_sandbox/Simplenote/NSTextStorage+Simplenote.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 127 |
```swift
import Foundation
open class SeparatorsView: UIView {
// MARK: - Public Properties
open var leftVisible = false {
didSet {
setNeedsDisplay()
}
}
open var leftColor = UIColor.simplenoteDividerColor {
didSet {
setNeedsDisplay()
}
}
open var leftWidthInPoints = CGFloat(3) {
didSet {
setNeedsDisplay()
}
}
open var topVisible = false {
didSet {
setNeedsDisplay()
}
}
open var topColor = UIColor.simplenoteDividerColor {
didSet {
setNeedsDisplay()
}
}
open var topHeightInPixels = CGFloat(1) {
didSet {
setNeedsDisplay()
}
}
open var topInsets = UIEdgeInsets.zero {
didSet {
setNeedsDisplay()
}
}
open var bottomVisible = false {
didSet {
setNeedsDisplay()
}
}
open var bottomColor = UIColor.simplenoteDividerColor {
didSet {
setNeedsDisplay()
}
}
open var bottomHeightInPixels = CGFloat(1) {
didSet {
setNeedsDisplay()
}
}
open var bottomInsets = UIEdgeInsets.zero {
didSet {
setNeedsDisplay()
}
}
open override var frame: CGRect {
didSet {
setNeedsDisplay()
}
}
// MARK: - UIView methods
convenience init() {
self.init(frame: CGRect.zero)
}
required override public init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
setupView()
}
open override func draw(_ rect: CGRect) {
super.draw(rect)
guard let ctx = UIGraphicsGetCurrentContext() else {
return
}
let scale = UIScreen.main.scale
ctx.clear(rect)
ctx.setShouldAntialias(false)
// Background
if backgroundColor != nil {
backgroundColor?.setFill()
ctx.fill(rect)
}
// Left Separator
if leftVisible {
leftColor.setStroke()
ctx.setLineWidth(leftWidthInPoints * scale)
ctx.move(to: CGPoint(x: bounds.minX, y: bounds.minY))
ctx.addLine(to: CGPoint(x: bounds.minX, y: bounds.maxY))
ctx.strokePath()
}
// Top Separator
if topVisible {
topColor.setStroke()
let lineWidth = topHeightInPixels / scale
ctx.setLineWidth(lineWidth)
ctx.move(to: CGPoint(x: topInsets.left, y: lineWidth))
ctx.addLine(to: CGPoint(x: bounds.maxX - topInsets.right, y: lineWidth))
ctx.strokePath()
}
// Bottom Separator
if bottomVisible {
bottomColor.setStroke()
ctx.setLineWidth(bottomHeightInPixels / scale)
ctx.move(to: CGPoint(x: bottomInsets.left, y: bounds.height))
ctx.addLine(to: CGPoint(x: bounds.maxX - bottomInsets.right, y: bounds.height))
ctx.strokePath()
}
}
fileprivate func setupView() {
backgroundColor = UIColor.clear
// Make sure this is re-drawn if the bounds change!
layer.needsDisplayOnBoundsChange = true
}
}
``` | /content/code_sandbox/Simplenote/SeparatorsView.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 702 |
```swift
import Foundation
// MARK: - Wraps access to all of the UserDefault Values
//
class Options: NSObject {
/// Shared Instance
///
@objc
static let shared = Options()
/// User Defaults: Convenience
///
private let defaults: UserDefaults
/// Designated Initializer
///
/// - Note: Should be *private*, but for unit testing purposes, we're opening this up.
///
init(defaults: UserDefaults = .standard) {
self.defaults = defaults
super.init()
migrateLegacyOptions()
migrateLegacyTheme()
}
}
// MARK: - Actual Options!
//
extension Options {
/// Indicates if the Notes List should be condensed (or not)
///
@objc
var condensedNotesList: Bool {
get {
return defaults.bool(forKey: .condensedNotes)
}
set {
defaults.set(newValue, forKey: .condensedNotes)
NotificationCenter.default.post(name: .SPCondensedNoteListPreferenceChanged, object: nil)
}
}
/// Indicates if it's the First Launch event was already handled
///
@objc
var firstLaunch: Bool {
get {
defaults.bool(forKey: .firstLaunch)
}
set {
defaults.set(newValue, forKey: .firstLaunch)
}
}
/// Returns the target Sort Mode for the Notes List
///
@objc
var listSortMode: SortMode {
get {
let payload = defaults.integer(forKey: .listSortMode)
return SortMode(rawValue: payload) ?? .modifiedNewest
}
set {
defaults.set(newValue.rawValue, forKey: .listSortMode)
SPTracker.trackSettingsNoteListSortMode(newValue.description)
NotificationCenter.default.post(name: .SPNotesListSortModeChanged, object: nil)
}
}
/// Indicates if Markdown should be enabled by default in new documents
///
@objc
var markdown: Bool {
get {
defaults.bool(forKey: .markdown)
}
set {
defaults.set(newValue, forKey: .markdown)
}
}
/// Returns the selected Theme
///
@objc
var theme: Theme {
get {
guard defaults.containsObject(forKey: .theme) else {
return Theme.defaultThemeForCurrentOS
}
let payload = defaults.integer(forKey: .theme)
return Theme(rawValue: payload) ?? Theme.defaultThemeForCurrentOS
}
set {
defaults.set(newValue.rawValue, forKey: .theme)
SPTracker.trackSettingsThemeUpdated(newValue.description)
NotificationCenter.default.post(name: .SPSimplenoteThemeChanged, object: nil)
}
}
var useBiometryInsteadOfPin: Bool {
get {
defaults.bool(forKey: .useBiometryInsteadOfPin)
}
set {
defaults.set(newValue, forKey: .useBiometryInsteadOfPin)
}
}
}
// MARK: - ObjC Convenience Methods
//
extension Options {
/// Returns the *Description* for the current List's Sort Mode
///
@objc
var listSortModeDescription: String {
return listSortMode.description
}
/// Returns the *Description* for the current List's Sort Mode
///
@objc
var themeDescription: String {
return theme.description
}
/// Nukes all of the Options. Useful for *logout* scenarios
///
@objc
func reset() {
defaults.removeObject(forKey: .theme)
defaults.removeObject(forKey: .listSortMode)
defaults.removeObject(forKey: .markdown)
defaults.removeObject(forKey: .useBiometryInsteadOfPin)
}
/// Returns the number of Preview Lines we should use, per note
///
@objc
var numberOfPreviewLines: Int {
return condensedNotesList ? Settings.numberOfPreviewLinesCondensed : Settings.numberOfPreviewLinesRegular
}
/// Index notes in spotlight
///
@objc
var indexNotesInSpotlight: Bool {
get {
defaults.bool(forKey: .indexNotesInSpotlight)
}
set {
defaults.set(newValue, forKey: .indexNotesInSpotlight)
}
}
}
// MARK: - Private
//
private extension Options {
func migrateLegacyOptions() {
guard defaults.containsObject(forKey: .listSortMode) == false else {
return
}
let legacySortAlphabetically = defaults.bool(forKey: .listSortModeLegacy)
let newMode: SortMode = legacySortAlphabetically ? .alphabeticallyAscending : .modifiedNewest
defaults.set(newMode.rawValue, forKey: .listSortMode)
defaults.removeObject(forKey: .listSortModeLegacy)
}
func migrateLegacyTheme() {
guard defaults.containsObject(forKey: .theme) == false, defaults.containsObject(forKey: .themeLegacy) else {
return
}
let newTheme: Theme = defaults.bool(forKey: .themeLegacy) ? .dark : .light
defaults.set(newTheme.rawValue, forKey: .theme)
}
}
// MARK: - Constants!
//
private enum Settings {
static let numberOfPreviewLinesRegular = 3
static let numberOfPreviewLinesCondensed = 1
}
``` | /content/code_sandbox/Simplenote/Options.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 1,103 |
```swift
import Foundation
// MARK: - AuthenticationValidator
//
struct AuthenticationValidator {
/// Minimum Password Length: Login
///
private let legacyPasswordLength = UInt(4)
/// Minimum Password Length: SignUp
///
private let strongPasswordLength = UInt(8)
/// Login Code Length
///
private let loginCodeLength = UInt(6)
/// Returns the Validation Result for a given Username
///
func performUsernameValidation(username: String) -> Result {
let predicate = NSPredicate.predicateForEmailValidation()
return predicate.evaluate(with: username) ? .success : .emailInvalid
}
/// Returns the Validation Result for a given Password (with its associated Username)
///
func performPasswordValidation(username: String, password: String, style: Style = .strong) -> Result {
let requiredPasswordLength = minimumPasswordLength(for: style)
guard password.count >= requiredPasswordLength else {
return .passwordTooShort(length: requiredPasswordLength)
}
guard style == .strong else {
return .success
}
guard password != username else {
return .passwordMatchesUsername
}
guard !password.contains(String.newline), !password.contains(String.tab) else {
return .passwordContainsInvalidCharacter
}
return .success
}
/// Defines the minimum allowed password length
///
private func minimumPasswordLength(for style: Style) -> UInt {
return (style == .legacy) ? legacyPasswordLength : strongPasswordLength
}
func performCodeValidation(code: String) -> Result {
if code.count >= loginCodeLength {
return .success
}
return .codeTooShort
}
}
// MARK: - Nested Types
//
extension AuthenticationValidator {
enum Style {
case legacy
case strong
}
enum Result: Equatable {
case success
case emailInvalid
case passwordMatchesUsername
case passwordTooShort(length: UInt)
case passwordContainsInvalidCharacter
case codeTooShort
}
}
// MARK: - Validation Results: String Conversion
//
extension AuthenticationValidator.Result: CustomStringConvertible {
var description: String {
switch self {
case .success:
// Not really needed. But for convenience reasons, it's super if this property isn't optional.
return String()
case .emailInvalid:
return NSLocalizedString("Your email address is not valid", comment: "Message displayed when email address is invalid")
case .passwordMatchesUsername:
return NSLocalizedString("Password cannot match email", comment: "Message displayed when password is invalid (Signup)")
case .passwordTooShort(let length):
let localized = NSLocalizedString("Password must contain at least %d characters", comment: "Message displayed when password is too short. Please preserve the Percent D!")
return String(format: localized, length)
case .passwordContainsInvalidCharacter:
return NSLocalizedString("Password must not contain tabs nor newlines", comment: "Message displayed when a password contains a disallowed character")
case .codeTooShort:
return NSLocalizedString("Login Code is too short", comment: "Message displayed when a login code is too short")
}
}
}
``` | /content/code_sandbox/Simplenote/AuthenticationValidator.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 669 |
```swift
import UIKit
// MARK: - SPCardView wraps content view in a view with rounded corners and a shadow
//
final class SPCardView: UIView {
private let containerView = UIView()
override init(frame: CGRect) {
super.init(frame: frame)
configure()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
configure()
}
deinit {
stopListeningToNotifications()
}
/// Add content view
/// - Parameters:
/// - view: content view (will be decorated with rounded corners and a shadow)
///
func addContentView(_ view: UIView) {
containerView.addFillingSubview(view)
}
}
// MARK: - Private
//
private extension SPCardView {
func configure() {
setupShadowView()
setupContainerView()
refreshStyle()
startListeningToNotifications()
}
func setupShadowView() {
let shadowView = SPShadowView(cornerRadius: Constants.cornerRadius,
roundedCorners: [.topLeft, .topRight])
addFillingSubview(shadowView)
}
func setupContainerView() {
addFillingSubview(containerView)
containerView.layer.cornerRadius = Constants.cornerRadius
containerView.layer.maskedCorners = [.layerMaxXMinYCorner, .layerMinXMinYCorner]
containerView.layer.masksToBounds = true
}
func refreshStyle() {
containerView.backgroundColor = UIColor.simplenoteCardBackgroundColor
}
}
// MARK: - Notifications
//
private extension SPCardView {
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 struct Constants {
static let cornerRadius: CGFloat = 10.0
}
``` | /content/code_sandbox/Simplenote/SPCardView.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 426 |
```swift
import Foundation
struct NoticeFactory {
static func linkCopied() -> Notice {
Notice(message: Messages.linkCopied, action: nil)
}
static func publishing() -> Notice {
Notice(message: Messages.publishing, action: nil)
}
static func unpublishing() -> Notice {
Notice(message: Messages.unpublishing, action: nil)
}
static func noteTrashed(onUndo: @escaping ()-> Void) -> Notice {
let action = NoticeAction(title: Messages.undo, handler: onUndo)
return Notice(message: Messages.trashed, action: action)
}
static func notesTrashed(_ notes: [Note], onUndo: @escaping ()-> Void) -> Notice {
let action = NoticeAction(title: Messages.undo, handler: onUndo)
return Notice(message: Messages.notesTrashed(notes.count), action: action)
}
static func unpublished(_ note: Note, onUndo: @escaping ()-> Void) -> Notice {
let action = NoticeAction(title: Messages.undo, handler: onUndo)
return Notice(message: Messages.unpublished, action: action)
}
static func published(_ note: Note, onCopy: @escaping ()-> Void) -> Notice {
let action = NoticeAction(title: Messages.copyLink, handler: onCopy)
return Notice(message: Messages.published, action: action)
}
static func networkError() -> Notice {
Notice(message: Messages.networkIssue, action: nil)
}
}
extension NoticeFactory {
private enum Messages {
static let copyLink = NSLocalizedString("Copy link", comment: "Copy link action")
static let linkCopied = NSLocalizedString("Link copied", comment: "Link Copied alert")
static let publishing = NSLocalizedString("Publishing note...", comment: "Notice of publishing action")
static let unpublishing = NSLocalizedString("Unpublishing note...", comment: "Notice of unpublishing action")
static let undo = NSLocalizedString("Undo", comment: "Undo action")
static let trashed = NSLocalizedString("Note Trashed", comment: "Note trashed notification")
static let unpublished = NSLocalizedString("Unpublish successful", comment: "Notice of publishing unsuccessful")
static let published = NSLocalizedString("Publish Successful", comment: "Notice up succesful publishing")
static let networkIssue = NSLocalizedString("A network connection is required. Please, check your connection and try again.", comment: "Network connection issue notificaiton")
static let noteTrashed = NSLocalizedString("%i Note Trashed", comment: "Note trashed notification")
static let notesTrashed = NSLocalizedString("%i Notes Trashed", comment: "Notes trashed notification")
static func notesTrashed(_ count: Int) -> String {
let template = count > 1 ? notesTrashed : noteTrashed
return String(format: template, count)
}
}
}
``` | /content/code_sandbox/Simplenote/NoticeFactory.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 598 |
```swift
import UIKit
// MARK: - TagListViewCellDeletionSource - source from where the tag is deleted
//
enum TagListViewCellDeletionSource {
case menu
case accessory
}
// MARK: - TagListViewCellDelegate
//
protocol TagListViewCellDelegate: AnyObject {
func tagListViewCellShouldDeleteTag(_ cell: TagListViewCell, source: TagListViewCellDeletionSource)
func tagListViewCellShouldRenameTag(_ cell: TagListViewCell)
}
// MARK: - TagListViewCell
//
class TagListViewCell: UITableViewCell {
@IBOutlet private(set) weak var textField: UITextField!
@IBOutlet private weak var stackView: UIStackView!
@IBOutlet private weak var trashButton: UIButton!
@IBOutlet private weak var trashButtonContainer: UIView!
/// Delegate
///
weak var delegate: TagListViewCellDelegate?
override func awakeFromNib() {
super.awakeFromNib()
refreshStyle()
// Don't use textField as an accessibility element.
// Instead use textField value as a cell accessibility label.
textField.isAccessibilityElement = false
}
override var accessibilityLabel: String? {
get {
return textField.text
}
set {
//
}
}
override func prepareForReuse() {
super.prepareForReuse()
refreshStyle()
reset()
}
override func willTransition(to state: UITableViewCell.StateMask) {
super.willTransition(to: state)
if state.isEmpty {
textField.resignFirstResponder()
}
}
override func setEditing(_ editing: Bool, animated: Bool) {
super.setEditing(editing, animated: animated)
let changesBlock = {
let isHidden = !editing
guard self.trashButtonContainer.isHidden != isHidden else {
return
}
self.trashButtonContainer.isHidden = isHidden
self.trashButtonContainer.alpha = isHidden ? UIKitConstants.alpha0_0 : UIKitConstants.alpha1_0
}
if animated {
UIView.animate(withDuration: UIKitConstants.animationShortDuration) {
changesBlock()
self.stackView.layoutIfNeeded()
}
} else {
changesBlock()
}
}
}
// MARK: - Private
//
private extension TagListViewCell {
func reset() {
accessoryType = .none
textField.delegate = nil
textField.isEnabled = false
delegate = nil
}
func refreshStyle() {
refreshCellStyle()
refreshSelectionStyle()
refreshComponentsStyle()
}
func refreshCellStyle() {
backgroundColor = .simplenoteBackgroundColor
}
func refreshSelectionStyle() {
let selectedView = UIView()
selectedView.backgroundColor = .simplenoteLightBlueColor
selectedBackgroundView = selectedView
}
func refreshComponentsStyle() {
textField.textColor = .simplenoteTextColor
trashButton.tintColor = .simplenoteTintColor
}
}
// MARK: - Actions
//
extension TagListViewCell {
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
return (action == #selector(rename(_:)) || action == #selector(delete(_:))) && !textField.isEditing
}
@objc
override func delete(_ sender: Any?) {
delegate?.tagListViewCellShouldDeleteTag(self, source: .menu)
}
@objc
override func rename(_ sender: Any?) {
delegate?.tagListViewCellShouldRenameTag(self)
}
@IBAction private func handleTapOnTrashButton() {
delegate?.tagListViewCellShouldDeleteTag(self, source: .accessory)
}
}
``` | /content/code_sandbox/Simplenote/TagListViewCell.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 757 |
```swift
import UIKit
protocol NoticeInteractionDelegate: AnyObject {
func noticePressBegan()
func noticePressEnded()
func actionWasTapped()
}
class NoticeView: UIView {
// MARK: Properties
//
@IBOutlet private weak var backgroundView: UIView!
@IBOutlet private weak var stackView: UIStackView!
@IBOutlet private weak var noticeLabel: UILabel!
@IBOutlet private weak var noticeButton: UIButton!
var message: String? {
get {
noticeLabel.text
}
set {
noticeLabel.text = newValue
}
}
var handler: (() -> Void)?
var actionTitle: String? {
get {
noticeButton.title(for: .normal)
}
set {
noticeButton.setTitle(newValue, for: .normal)
noticeButton.isHidden = newValue == nil
}
}
weak var delegate: NoticeInteractionDelegate?
// MARK: Initialization
//
override func awakeFromNib() {
super.awakeFromNib()
setupView()
}
// MARK: View Layout
//
private func setupView() {
translatesAutoresizingMaskIntoConstraints = false
setupViewStyles()
setupGestureRecognizers()
configureAccessibilityIfNeeded()
layoutIfNeeded()
}
private func setupGestureRecognizers() {
let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(viewWasLongPressed(_:)))
addGestureRecognizer(longPressGesture)
}
private func setupViewStyles() {
backgroundColor = .clear
backgroundView.backgroundColor = .simplenoteNoticeViewBackgroundColor
backgroundView.layer.cornerRadius = Constants.cornerRadius
noticeLabel.textColor = .simplenoteTextColor
noticeButton.setTitleColor(.simplenoteTintColor, for: .normal)
noticeButton.setTitleColor(.simplenoteCardDismissButtonHighlightedBackgroundColor, for: .highlighted)
noticeButton.isHidden = true
noticeButton.titleLabel?.font = UIFont.preferredFont(for: .subheadline, weight: .semibold)
noticeButton.titleLabel?.adjustsFontForContentSizeCategory = true
}
private func configureAccessibilityIfNeeded() {
switch traitCollection.preferredContentSizeCategory {
case .accessibilityLarge, .accessibilityExtraLarge, .accessibilityExtraExtraLarge, .accessibilityExtraExtraExtraLarge:
stackView.axis = .vertical
default:
return
}
}
// MARK: Action
//
@IBAction func noticeButtonWasTapped(_ sender: Any) {
delegate?.actionWasTapped()
handler?()
}
}
extension NoticeView {
// MARK: Gesture Recognizers
//
@objc
private func viewWasLongPressed(_ gesture: UIGestureRecognizer) {
switch gesture.state {
case .began:
longPressBegan()
case .ended:
longPressEnded()
default:
return
}
}
private func longPressBegan() {
delegate?.noticePressBegan()
}
private func longPressEnded() {
delegate?.noticePressEnded()
}
}
private struct Constants {
static let cornerRadius = CGFloat(25)
static let nibName = "NoticeView"
}
``` | /content/code_sandbox/Simplenote/NoticeView.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 662 |
```swift
import Foundation
// MARK: - SPEditorTextView
//
extension SPEditorTextView {
/// Text with attachments converted to markdown
@objc
var plainText: String {
return NSAttributedStringToMarkdownConverter.convert(string: attributedText)
}
/// Selected text with attachments converted to markdown
var plainSelectedText: String? {
guard selectedRange.location != NSNotFound else {
return nil
}
let selectedAttributedText = attributedText.attributedSubstring(from: selectedRange)
return NSAttributedStringToMarkdownConverter.convert(string: selectedAttributedText)
}
open override func copy(_ sender: Any?) {
UIPasteboard.general.string = plainSelectedText
}
open override func cut(_ sender: Any?) {
let text = plainSelectedText
super.cut(sender)
UIPasteboard.general.string = text
}
}
// MARK: - Observer content position
//
extension SPEditorTextView {
open override var contentSize: CGSize {
didSet {
onContentPositionChange?()
}
}
open override var contentOffset: CGPoint {
didSet {
onContentPositionChange?()
}
}
open override var contentInset: UIEdgeInsets {
didSet {
onContentPositionChange?()
}
}
}
``` | /content/code_sandbox/Simplenote/SPEditorTextView+Simplenote.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 264 |
```swift
import Foundation
struct NoticeAction {
let title: String
let handler: () -> Void
}
``` | /content/code_sandbox/Simplenote/NoticeAction.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 23 |
```swift
import UIKit
// MARK: - SPCardTransitioningManager: Manages card-like presentation of a view controller
//
final class SPCardTransitioningManager: NSObject, UIViewControllerTransitioningDelegate {
private weak var presentationController: SPCardPresentationController?
/// Delegate for presentation (and dismissal) related events
///
weak var presentationDelegate: SPCardPresentationControllerDelegate?
func presentationController(forPresented presented: UIViewController,
presenting: UIViewController?,
source: UIViewController) -> UIPresentationController? {
let presentationController = SPCardPresentationController(presentedViewController: presented,
presenting: presenting)
presentationController.presentationDelegate = presentationDelegate
self.presentationController = presentationController
return presentationController
}
func animationController(forPresented presented: UIViewController,
presenting: UIViewController,
source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return SPCardPresentationAnimator()
}
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return SPCardDismissalAnimator()
}
func interactionControllerForDismissal(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
return presentationController?.transitionInteractor
}
}
``` | /content/code_sandbox/Simplenote/SPCardTransitioningManager.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 256 |
```swift
import Foundation
// MARK: - EmailVerification
//
struct EmailVerification {
let token: EmailVerificationToken?
let sentTo: String?
}
// MARK: - EmailVerificationToken
//
struct EmailVerificationToken: Decodable {
let username: String
}
// MARK: - Init from payload
//
extension EmailVerification {
/// Initializes an EmailVerification entity from a dictionary
///
init(payload: [AnyHashable: Any]) {
token = {
guard let dataString = payload[EmailVerificationKeys.token.rawValue] as? String,
let data = dataString.data(using: .utf8) else {
return nil
}
return try? JSONDecoder().decode(EmailVerificationToken.self, from: data)
}()
sentTo = payload[EmailVerificationKeys.sentTo.rawValue] as? String
}
}
// MARK: - CodingKeys
//
private enum EmailVerificationKeys: String {
case token
case sentTo = "sent_to"
}
``` | /content/code_sandbox/Simplenote/EmailVerification.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 208 |
```swift
//
// StoreConstants.swift
// Simplenote
//
// Created by Jorge Leandro Perez on 10/27/22.
//
import Foundation
// MARK: - Settings
//
enum StoreConstants {
static let platform = "iOS"
static let activeSubscriptionLevel = "sustainer"
}
``` | /content/code_sandbox/Simplenote/StoreConstants.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 67 |
```swift
import Foundation
enum WidgetError: Error {
case appConfigurationError
case fetchError
}
extension WidgetError {
/// Returns the Error Title, for Alert purposes
///
var title: String {
switch self {
case .appConfigurationError:
return NSLocalizedString("Main App is not configured", comment: "App configuration error title")
case .fetchError:
return NSLocalizedString("Could not fetch entities", comment: "Fetch error title")
}
}
/// Returns the Error Message, for Alert purposes
///
var message: String {
switch self {
case .appConfigurationError:
return NSLocalizedString("Simplenote must be configured and logged in to setup widgets", comment: "Message displayed when app is not configured")
case .fetchError:
return NSLocalizedString("Attempt to fetch entities failed. Please try again later.", comment: "Data Fetch error message")
}
}
}
``` | /content/code_sandbox/Simplenote/WidgetError.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 194 |
```swift
import UIKit
// MARK: - TableHeaderViewCell
//
final class TableHeaderViewCell: UITableViewCell {
private let titleLabel = UILabel()
/// Wraps the TitleLabel's Text Property
///
var title: String? {
get {
titleLabel.text
}
set {
titleLabel.text = newValue
}
}
// MARK: - Initializers
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: .default, reuseIdentifier: reuseIdentifier)
configure()
}
required init?(coder: NSCoder) {
fatalError("Unsupported Initializer")
}
}
// MARK: - Private API(s)
//
private extension TableHeaderViewCell {
func configure() {
contentView.addFillingSubview(titleLabel,
edgeInsets: Constants.titleLabelExtraInsets,
target: .layoutMargins)
separatorInset = .zero
selectionStyle = .none
accessoryType = .none
reloadBackgroundStyles()
reloadTextStyles()
}
func reloadBackgroundStyles() {
backgroundColor = .clear
}
func reloadTextStyles() {
titleLabel.textColor = .simplenoteSecondaryTextColor
titleLabel.font = UIFont.preferredFont(for: .subheadline, weight: .regular)
}
}
private struct Constants {
static let titleLabelExtraInsets = UIEdgeInsets(top: 8, left: 0, bottom: -2, right: 0)
}
``` | /content/code_sandbox/Simplenote/TableHeaderViewCell.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 295 |
```swift
import Foundation
import SimplenoteSearch
extension SearchQuery {
convenience init(searchText: String) {
self.init(searchText: searchText, settings: .default)
}
}
extension SearchQuerySettings {
static var `default`: SearchQuerySettings {
let localizedKeyword = NSLocalizedString("tag:", comment: "Search Operator for tags. Please preserve the semicolons when translating!")
return SearchQuerySettings(tagsKeyword: "tag:", localizedTagKeyword: localizedKeyword)
}
}
``` | /content/code_sandbox/Simplenote/SearchQuery+Simplenote.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 101 |
```swift
import Foundation
extension Note {
var publishState: PublishState {
if published && !publishURL.isEmpty {
return .published
}
if published && publishURL.isEmpty {
return .publishing
}
if !published && !publishURL.isEmpty {
return .unpublishing
}
return .unpublished
}
}
enum PublishState {
case published
case publishing
case unpublished
case unpublishing
}
``` | /content/code_sandbox/Simplenote/Note+Publish.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 98 |
```swift
import Foundation
import UIKit
// MARK: - BannerView
//
class BannerView: UIView {
@IBOutlet
private var backgroundView: UIView!
@IBOutlet
private var titleLabel: UILabel!
@IBOutlet
private var detailsLabel: UILabel!
@IBOutlet
private var topConstraint: NSLayoutConstraint!
@IBOutlet
private var widthConstraint: NSLayoutConstraint!
@objc
var appliesTopInset: Bool = false {
didSet {
topConstraint.constant = appliesTopInset ? Metrics.defaultTopInset : .zero
}
}
var onPress: (() -> Void)?
var preferredWidth: CGFloat? {
didSet {
guard let preferredWidth else {
return
}
widthConstraint.constant = preferredWidth
}
}
// MARK: - Overridden Methods
override func awakeFromNib() {
super.awakeFromNib()
refreshInterface()
}
// MARK: - Actions
@IBAction
func bannerWasPresssed() {
onPress?()
}
}
// MARK: - Private API(s)
//
private extension BannerView {
func refreshInterface(with style: Style? = nil) {
guard let style else {
return
}
titleLabel.text = style.title
detailsLabel.text = style.details
titleLabel.textColor = style.textColor
detailsLabel.textColor = style.textColor
backgroundView.backgroundColor = style.backgroundColor
backgroundView.layer.cornerRadius = Metrics.defaultCornerRadius
}
}
// MARK: - Style
//
private struct Style {
let title: String
let details: String
let textColor: UIColor
let backgroundColor: UIColor
}
private extension Style {
// Leaving these styles in cause we may want them back someday
static var sustainer: Style {
Style(title: NSLocalizedString("You are a Simplenote Sustainer", comment: "Current Sustainer Title"),
details: NSLocalizedString("Thank you for your continued support", comment: "Current Sustainer Details"),
textColor: .white,
backgroundColor: .simplenoteSustainerViewBackgroundColor)
}
static var notSubscriber: Style {
Style(title: NSLocalizedString("Become a Simplenote Sustainer", comment: "Become a Sustainer Title"),
details: NSLocalizedString("Support your favorite notes app to help unlock future features", comment: "Become a Sustainer Details"),
textColor: .white,
backgroundColor: .simplenoteBlue50Color)
}
}
// MARK: - Metrics
//
private enum Metrics {
static let defaultTopInset: CGFloat = 19
static let defaultCornerRadius: CGFloat = 8
}
``` | /content/code_sandbox/Simplenote/BannerView.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 549 |
```swift
import Foundation
import AutomatticTracks
/// This exists to bridge CrashLogging with Objective-C. Once the App Delegate is moved over to Swift,
/// this shim can be removed, and the cache methods moved to a `CrashLogging` extension. At that time,
/// you, future developer, can just set up the Crash Logging system in the App Delegate using `SNCrashLoggingDataProvider`.
@objc(CrashLogging)
class CrashLoggingShim: NSObject {
@objc
static let shared = CrashLoggingShim()
private var crashLogging: CrashLogging?
@objc
func start(withSimperium simperium: Simperium) {
crashLogging = {
let dataProvider = SNCrashLoggingDataProvider(withSimperium: simperium)
let logger = CrashLogging(dataProvider: dataProvider)
return try? logger.start()
}()
}
@objc
func cacheUser(_ user: SPUser) {
CrashLoggingCache.emailAddress = user.email
crashLogging?.setNeedsDataRefresh()
}
func crash() {
crashLogging?.crash()
}
func logError(_ error: Error) {
crashLogging?.logError(error)
}
@objc static func cacheOptOutSetting(_ didOptOut: Bool) {
CrashLoggingCache.didOptOut = didOptOut
}
}
private class SNCrashLoggingDataProvider: CrashLoggingDataProvider {
private let simperium: Simperium
init(withSimperium simperium: Simperium) {
self.simperium = simperium
}
var sentryDSN: String {
return SPCredentials.sentryDSN
}
var userHasOptedOut: Bool {
if let analyticsEnabledSetting = simperium.preferencesObject().analytics_enabled {
return !analyticsEnabledSetting.boolValue
}
return CrashLoggingCache.didOptOut
}
var buildType: String {
return BuildConfiguration.current.description
}
var currentUser: TracksUser? {
/// Prefer data from the up-to-date simperium user
if let user = self.simperium.user, let email = user.email {
return TracksUser(userID: email, email: email, username: email)
}
/// If that's not available, fall back to the cache instead
if let user = CrashLoggingCache.cachedUser, let email = user.emailAddress {
return TracksUser(userID: email, email: email, username: email)
}
return nil
}
}
/*
Provide a cache for user settings.
Simperium works completely asynchronously, but we need to have the ability to recall user data at launch
to send crash reports that are attributed to specific users. The flow for this looks something like this:
- First Run : No user data this cache doesn't help us
- Post-login: User data is set and cached
- User changes analytics opt-in settings: Updated user data is cached
- App Crashes
- First Run after Crash: User data is retrieved from the crash and used to identify the user (and their opt-in settings)
SNCrashLoggingDataProvider will use this cache in `currentUser` to fetch data on the user.
*/
private struct CrashLoggingCache {
struct User: Codable {
var emailAddress: String?
var didOptOut: Bool = true
}
static var emailAddress: String? {
get {
return cachedUser?.emailAddress
}
set {
var updatedUser = cachedUser ?? User()
updatedUser.emailAddress = newValue
cachedUser = updatedUser
}
}
static var didOptOut: Bool {
get {
return cachedUser?.didOptOut ?? true
}
set {
var updatedUser = cachedUser ?? User()
updatedUser.didOptOut = newValue
cachedUser = updatedUser
}
}
private(set)
static var cachedUser: User? {
get {
guard let data = UserDefaults.standard.object(forKey: key) as? Data else {
return nil
}
return try? PropertyListDecoder().decode(User.self, from: data)
}
set {
guard let data = try? PropertyListEncoder().encode(newValue) else {
return
}
UserDefaults.standard.set(data, forKey: key)
}
}
private static let key = "crash-logging-cache-key"
}
``` | /content/code_sandbox/Simplenote/CrashLogging.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 936 |
```swift
import UIKit
class NoticePresenter {
// MARK: Properties
//
private var noticeView: UIView?
private var containerView: PassthruView?
private var noticeVariableConstraint: NSLayoutConstraint?
private var keyboardHeight: CGFloat = .zero
private var keyboardFloats: Bool = false
private var keyboardNotificationTokens: [Any]?
private var keyWindow: UIWindow? {
return UIApplication.shared.foregroundSceneWindows.first(where: { $0.isKeyWindow })
}
private var windowFrame: CGRect {
return keyWindow?.frame ?? .zero
}
private var bottomConstraintConstant: CGFloat {
let constant = Constants.bottomMarginConstant
if keyboardFloats || keyboardHeight == .zero {
return constant
}
return constant - keyboardHeight
}
// MARK: Lifecycle
//
deinit {
stopListeningToKeyboardNotifications()
}
func startListeningToKeyboardNotifications() {
keyboardNotificationTokens = addKeyboardObservers()
}
func stopListeningToKeyboardNotifications() {
guard let tokens = keyboardNotificationTokens else {
return
}
removeKeyboardObservers(with: tokens)
keyboardNotificationTokens = nil
}
// MARK: Presenting Methods
//
func presentNoticeView(_ noticeView: NoticeView, completion: @escaping () -> Void) {
guard let containerView = prepareContainerView() else {
return
}
self.noticeView = noticeView
add(view: noticeView, into: containerView)
display(view: noticeView, in: containerView) {
completion()
}
}
private func prepareContainerView() -> PassthruView? {
guard let keyWindow = keyWindow else {
return nil
}
let containerView = PassthruView(frame: .zero)
self.containerView = containerView
keyWindow.addFillingSubview(containerView)
return containerView
}
private func add(view: UIView, into containerView: PassthruView) {
containerView.addSubview(view)
noticeVariableConstraint = view.topAnchor.constraint(equalTo: containerView.bottomAnchor)
noticeVariableConstraint?.isActive = true
view.centerXAnchor.constraint(equalTo: containerView.centerXAnchor).isActive = true
containerView.layoutIfNeeded()
}
private func display(view: UIView, in containerView: UIView, completion: @escaping () -> Void) {
prepareConstraintFor(view: view, in: containerView)
UIView.animate(withDuration: UIKitConstants.animationShortDuration, animations: {
containerView.layoutIfNeeded()
}, completion: { _ in
completion()
})
}
private func prepareConstraintFor(view: UIView, in containerView: UIView) {
noticeVariableConstraint?.isActive = false
let constant = bottomConstraintConstant
noticeVariableConstraint = view.bottomAnchor.constraint(equalTo: containerView.bottomAnchor, constant: constant)
noticeVariableConstraint?.isActive = true
}
// MARK: Dismissing Methods
//
func dismissNotification(withDuration duration: TimeInterval, completion: @escaping () -> Void) {
guard let containerView = containerView,
let noticeView = noticeView else {
return
}
UIView.animate(withDuration: duration,
delay: .zero,
options: [.allowUserInteraction]) {
noticeView.alpha = .zero
containerView.alpha = .zero
} completion: { (_) in
noticeView.removeFromSuperview()
containerView.removeFromSuperview()
completion()
}
self.noticeView = nil
self.containerView = nil
}
}
// MARK: Keyboard Observable
//
extension NoticePresenter: KeyboardObservable {
func keyboardDidChangeFrame(beginFrame: CGRect?, endFrame: CGRect?, animationDuration: TimeInterval?, animationCurve: UInt?) {
guard let endFrame = endFrame,
let animationCurve = animationCurve,
let animationDuration = animationDuration else {
return
}
updateKeyboardHeight(with: endFrame)
animateNoticeToNewKeyboardLocation(frame: endFrame, curve: animationCurve, animationDuration: animationDuration)
}
func keyboardWillChangeFrame(beginFrame: CGRect?, endFrame: CGRect?, animationDuration: TimeInterval?, animationCurve: UInt?) {
guard let endFrame = endFrame,
let animationCurve = animationCurve,
let animationDuration = animationDuration else {
return
}
updateKeyboardHeight(with: endFrame)
animateNoticeToNewKeyboardLocation(frame: endFrame, curve: animationCurve, animationDuration: animationDuration)
}
private func updateKeyboardHeight(with frame: CGRect) {
keyboardHeight = frame.intersection(windowFrame).height
keyboardFloats = frame.maxY < windowFrame.height
}
private func animateNoticeToNewKeyboardLocation(frame: CGRect, curve: UInt, animationDuration: TimeInterval) {
guard let containerView = containerView else {
return
}
let animationOptions = UIView.AnimationOptions(arrayLiteral: .beginFromCurrentState, .init(rawValue: curve))
noticeVariableConstraint?.constant = bottomConstraintConstant
UIView.animate(withDuration: animationDuration, delay: .zero, options: animationOptions) {
containerView.layoutIfNeeded()
}
}
}
private struct Constants {
static let bottomMarginConstant = CGFloat(-50)
}
``` | /content/code_sandbox/Simplenote/NoticePresenter.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 1,075 |
```swift
import Foundation
import UniformTypeIdentifiers
import CoreData
public class RecoveryUnarchiver {
private let fileManager: FileManager
private let simperium: Simperium
public init(fileManager: FileManager = .default, simperium: Simperium) {
self.fileManager = fileManager
self.simperium = simperium
}
// MARK: Restore
//
public func insertNotesFromRecoveryFilesIfNeeded() {
guard let recoveryURL = fileManager.recoveryDirectoryURL(),
let recoveryFiles = try? fileManager.contentsOfDirectory(at: recoveryURL, includingPropertiesForKeys: nil),
!recoveryFiles.isEmpty else {
return
}
recoveryFiles.forEach { url in
insertNote(from: url)
try? fileManager.removeItem(at: url)
}
}
private func insertNote(from url: URL) {
guard let data = fileManager.contents(atPath: url.path),
let recoveredContent = String(data: data, encoding: .utf8),
let note = simperium.notesBucket.insertNewObject() as? Note else {
return
}
var content = Constants.recoveredContentHeader
content += "\n\n"
content += recoveredContent
note.content = content
note.modificationDate = Date()
note.creationDate = Date()
note.markdown = UserDefaults.standard.bool(forKey: .markdown)
simperium.save()
}
}
private struct Constants {
static let recoveredContentHeader = NSLocalizedString("Recovered Note Cotent - ", comment: "Header to put on any files that need to be recovered")
}
``` | /content/code_sandbox/Simplenote/RecoveryUnarchiver.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 343 |
```objective-c
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface NSMutableAttributedString (Checklists)
/// Replaces Checklist Markers with a SPTextAttachment at the exact same location.
///
/// @param color: Tinting Color to be applied over the Image
/// @param sizingFont: Font that should be used to determine the Attachment Size
/// @param allowsMultiplePerLine: When **YES** we'll support multiple Checklists Image in the same line. Useful for the Notes List.
///
/// @Discussion
/// When Multiple Lines are allowed, we'll prepend a space to any attachment that's not at location Zero. Otherwise notes that look like
/// the following, will definitely look bad: the Checklist Image would end up by the preceding word, without spacing.
///
/// `Word -[ ] Item - [ ] Item - [ ] Item`
///
/// @Note
/// We're expecting a sizingFont because in the NotesList a UILabel is used (which lacks the full TextKit Stack),
/// which makes it impossible to determine the current Font, from within the NSTextAttachment instance.
///
- (void)processChecklistsWithColor:(UIColor *)color
sizingFont:(UIFont *)sizingFont
allowsMultiplePerLine:(BOOL)allowsMultiplePerLine;
@end
NS_ASSUME_NONNULL_END
``` | /content/code_sandbox/Simplenote/NSMutableAttributedString+Styling.h | objective-c | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 268 |
```objective-c
#import <Simperium/SPManagedObject.h>
@interface Preferences: SPManagedObject
@property (nullable, nonatomic, strong) NSArray<NSString *> *recent_searches;
@property (nullable, nonatomic, copy) NSNumber *analytics_enabled;
@property (nullable, nonatomic, copy) NSDate *subscription_date;
@property (nullable, nonatomic, copy) NSString *subscription_level;
@property (nullable, nonatomic, copy) NSString *subscription_platform;
@property (nullable, nonatomic, copy) NSNumber *was_sustainer;
@end
``` | /content/code_sandbox/Simplenote/Preferences.h | objective-c | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 113 |
```swift
//
// StoreManager.swift
// Simplenote
//
// Created by Jorge Leandro Perez on 10/26/22.
//
import Foundation
import StoreKit
// MARK: - StoreError
//
enum StoreError: Error {
case failedVerification
}
// MARK: - StoreManager
//
class StoreManager {
// MARK: - Static
//
static let shared = StoreManager()
// MARK: - Aliases
//
typealias SubscriptionStatus = Product.SubscriptionInfo.Status
typealias RenewalInfo = Product.SubscriptionInfo.RenewalInfo
// MARK: - Private Properties
private var updateListenerTask: Task<Void, Error>?
private(set) var storeProductMap: [StoreProduct: Product] = [:]
private(set) var purchasedProducts: [Product] = []
private(set) var subscriptionGroupStatus: SubscriptionStatus? {
didSet {
refreshSimperiumPreferences(status: subscriptionGroupStatus)
}
}
// MARK: - Public Properties
var isActiveSubscriber: Bool {
guard let subscriptionGroupStatus else {
return false
}
return subscriptionGroupStatus.isActive
}
// MARK: - Deinit
deinit {
updateListenerTask?.cancel()
}
// MARK: - Public API(s)
/// Initialization involves three major steps:
///
/// 1. Listen for Pending Transactions
/// 2. Request the Known Products
/// 3. Refresh the Purchased Products
/// 4. Refresh the SubscriptionGroup Status (and update Core Data / refresh UI all over!)
///
/// This API should be invoked shortly after the Launch Sequence is complete.
///
func initialize() {
NSLog("[StoreManager] Initializing...")
updateListenerTask = listenForTransactions()
Task {
await refreshKnownProducts()
await refreshPurchasedProducts()
await refreshSubscriptionGroupStatus()
}
}
/// Purchases the specified Product (as long as we don't own it already?)
///
func purchase(storeProduct: StoreProduct) {
guard let product = storeProductMap[storeProduct], isActiveSubscriber == false else {
return
}
Task {
do {
try await purchase(product: product)
await SPTracker.trackSustainerPurchaseCompleted(storeProduct: storeProduct)
} catch {
NSLog("[StoreManager] Purchase Failed \(error)")
}
}
}
/// Returns the Display Price for a given Product
///
func displayPrice(for storeProduct: StoreProduct) -> String? {
guard let product = storeProductMap[storeProduct] else {
return nil
}
return product.displayPrice
}
/// Restores Purchases. Shouldn't be required, but review guideliens dictate we provide an explicit action!
///
func restorePurchases(completion: @escaping (Bool) -> Void) {
Task {
await refreshPurchasedProducts()
await refreshSubscriptionGroupStatus()
Task { @MainActor in
completion(isActiveSubscriber)
}
}
}
}
// MARK: - Private API(s)
//
private extension StoreManager {
func listenForTransactions() -> Task<Void, Error> {
return Task.detached {
for await result in Transaction.updates {
do {
let transaction = try self.checkVerified(result)
await self.refreshPurchasedProducts()
await self.refreshSubscriptionGroupStatus()
await transaction.finish()
} catch {
NSLog("[StoreKit] Transaction failed verification. Error \(error)")
}
}
}
}
@MainActor
func refreshKnownProducts() async {
do {
let allProducts = try await Product.products(for: StoreProduct.allIdentifiers)
storeProductMap = self.buildStoreProductMap(products: allProducts)
NSLog("[StoreKit] Retrieved \(storeProductMap.count) Subscription Products")
} catch {
NSLog("[StoreKit] Failed product request from the App Store server: \(error)")
}
}
/// The `purchasedProducts` collection us determine if a given `Product` instance has been purchased, or not.
///
@MainActor
func refreshPurchasedProducts() async {
var newPurchasedProducts: [Product] = []
for await result in Transaction.currentEntitlements {
do {
let transaction = try checkVerified(result)
if let subscription = storeProductMap.values.first(where: { $0.id == transaction.productID }) {
newPurchasedProducts.append(subscription)
}
} catch {
NSLog("[StoreKit] Failed to refresh Current Entitlements: \(error)")
}
}
purchasedProducts = newPurchasedProducts
}
/// - Important: Simplenote has a single Subscription Group. `product.subscription.status` represents the entire subscription group status
///
@MainActor
func refreshSubscriptionGroupStatus() async {
do {
let newStatus = try await storeProductMap.values.first?.subscription?.status.first
subscriptionGroupStatus = newStatus
} catch {
NSLog("[StoreKit] Failed to refresh the Subscription Group Status: \(error)")
}
}
@discardableResult
func purchase(product: Product) async throws -> Transaction? {
let result = try await product.purchase()
switch result {
case .success(let verification):
let transaction = try checkVerified(verification)
await refreshPurchasedProducts()
await refreshSubscriptionGroupStatus()
await transaction.finish()
return transaction
case .userCancelled, .pending:
return nil
default:
return nil
}
}
}
// MARK: - Private Helpers
//
private extension StoreManager {
func buildStoreProductMap(products: [Product]) -> [StoreProduct: Product] {
return products.reduce([StoreProduct: Product]()) { partialResult, product in
guard let storeProduct = StoreProduct.findStoreProduct(identifier: product.id) else {
return partialResult
}
var updated = partialResult
updated[storeProduct] = product
return updated
}
}
func isPurchased(_ product: Product) -> Bool {
purchasedProducts.contains(product)
}
func checkVerified<T>(_ result: VerificationResult<T>) throws -> T {
switch result {
case .unverified:
throw StoreError.failedVerification
case .verified(let safe):
return safe
}
}
}
// MARK: - Simperium Kung Fu
//
private extension StoreManager {
func refreshSimperiumPreferences(status: SubscriptionStatus?) {
let simperium = SPAppDelegate.shared().simperium
simperium.managedObjectContext().perform {
self.refreshSimperiumPreferences(simperium: simperium, status: status)
}
}
func refreshSimperiumPreferences(simperium: Simperium, status: SubscriptionStatus?) {
let preferences = simperium.preferencesObject()
guard mustUpdatePreferences(preferences: preferences) else {
return
}
if let status, status.isActive {
preferences.subscription_level = subscriptionLevel(from: status)
preferences.subscription_date = subscriptionDate(from: status)
preferences.subscription_platform = StoreConstants.platform
}
simperium.save()
}
func mustUpdatePreferences(preferences: Preferences) -> Bool {
guard let platform = preferences.subscription_platform else {
return true
}
return platform.isEmpty || platform == StoreConstants.platform
}
func subscriptionDate(from status: SubscriptionStatus) -> Date? {
do {
return try checkVerified(status.transaction).purchaseDate
} catch {
NSLog("[StoreManager] Error Verifying Transaction")
return nil
}
}
func subscriptionLevel(from status: SubscriptionStatus) -> String? {
guard status.isActive else {
return nil
}
return StoreConstants.activeSubscriptionLevel
}
}
// MARK: - SubscriptionStatus Helpers
//
private extension Product.SubscriptionInfo.Status {
var isActive: Bool {
state == .subscribed || state == .inGracePeriod
}
}
``` | /content/code_sandbox/Simplenote/StoreManager.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 1,699 |
```swift
import Foundation
// MARK: - NumberFormatter Extension
//
extension NumberFormatter {
/// Number formatter with decimal style
///
static let decimalFormatter: NumberFormatter = {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
return formatter
}()
}
``` | /content/code_sandbox/Simplenote/NumberFormatter+Simplenote.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 59 |
```objective-c
//
// SPConstants.h
// Simplenote
//
// Created by Jorge Leandro Perez on 12/22/14.
//
#import <Foundation/Foundation.h>
#pragma mark ================================================================================
#pragma mark Constants
#pragma mark ================================================================================
extern NSString *const kSimperiumBaseURL;
extern NSString *const kSimperiumForgotPasswordURL;
extern NSString *const kSimperiumTermsOfServiceURL;
extern NSString *const kSimperiumPreferencesObjectKey;
extern NSString *const kAutomatticAnalyticLearnMoreURL;
extern NSString *const kShareExtensionGroupName;
extern NSString *const kSimplenoteWPServiceName;
extern NSString *const kSelectedTagKey;
extern NSString *const kSimplenoteTrashKey;
extern NSString *const kSimplenoteUntaggedKey;
extern NSString *const kSimplenoteUseBiometryKey;
extern NSString *const kSignInErrorNotificationName;
extern NSString *const kPinTimeoutPreferencesKey;
extern NSString *const kWordPressAuthURL;
``` | /content/code_sandbox/Simplenote/SPConstants.h | objective-c | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 212 |
```swift
import Foundation
import CoreData
enum CoreDataUsageType {
case standard
case intents
case widgets
}
@objcMembers
class CoreDataManager: NSObject {
// MARK: Core Data
private(set) var managedObjectModel: NSManagedObjectModel!
private(set) var managedObjectContext: NSManagedObjectContext!
private(set) var persistentStoreCoordinator: NSPersistentStoreCoordinator!
init(_ storageURL: URL, storageSettings: StorageSettings = StorageSettings(), for usageType: CoreDataUsageType = .standard) throws {
super.init()
managedObjectModel = NSManagedObjectModel(contentsOf: storageSettings.modelURL)!
managedObjectContext = buildMainContext()
persistentStoreCoordinator = try buildStoreCoordinator(with: managedObjectModel, storageURL: storageURL)
setupStackIfNeeded(mainContext: managedObjectContext, psc: persistentStoreCoordinator, for: usageType)
}
private func buildMainContext() -> NSManagedObjectContext {
let moc = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
moc.undoManager = nil
return moc
}
private func buildStoreCoordinator(with model: NSManagedObjectModel, storageURL: URL) throws -> NSPersistentStoreCoordinator {
let psc = NSPersistentStoreCoordinator(managedObjectModel: managedObjectModel)
let options = [NSMigratePersistentStoresAutomaticallyOption: true,
NSInferMappingModelAutomaticallyOption: true]
NSLog(" Loading PersistentStore at URL: \(storageURL)")
do {
try psc.addPersistentStore(ofType: NSSQLiteStoreType,
configurationName: nil,
at: storageURL,
options: options)
} catch {
throw NSError(domain: Constants.errorDomain, code: .zero, userInfo: nil)
}
return psc
}
private func setupStackIfNeeded(mainContext: NSManagedObjectContext, psc: NSPersistentStoreCoordinator, for usageType: CoreDataUsageType) {
switch usageType {
case .standard:
break
case .intents, .widgets:
managedObjectContext.persistentStoreCoordinator = persistentStoreCoordinator
}
}
}
private struct Constants {
static let errorDomain = "CoreDataManager"
}
``` | /content/code_sandbox/Simplenote/CoreDataManager.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 456 |
```objective-c
//
// Use this file to import your target's public headers that you would like to expose to Swift.
//
#pragma mark - External
#import <Simperium/Simperium.h>
#pragma mark - Simplenote-Y
#import "Note.h"
#import "Tag.h"
#import "Settings.h"
#import "PersonTag.h"
#import "SPAppDelegate.h"
#import "SPConstants.h"
#import "SPEditorTextView.h"
#import "SPInteractiveTextStorage.h"
#import "SPMarkdownPreviewViewController.h"
#import "SPNotifications.h"
#import "SPObjectManager.h"
#import "SPRatingsHelper.h"
#import "SPSettingsViewController.h"
#import "SPTextView.h"
#import "SPTextField.h"
#import "SPTableViewController.h"
#import "SPNoteListViewController.h"
#import "SPNoteEditorViewController.h"
#import "SPAddCollaboratorsViewController.h"
#import "SPTracker.h"
#import "SPTagEntryField.h"
#import "WPAuthHandler.h"
#import "NSManagedObjectContext+CoreDataExtensions.h"
#pragma mark - Extensions
#import "UIImage+Colorization.h"
#import "NSMutableAttributedString+Styling.h"
#import "NSString+Condensing.h"
#import "Simperium+Simplenote.h"
#import "SPNavigationController.h"
``` | /content/code_sandbox/Simplenote/Simplenote-Bridging-Header.h | objective-c | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 258 |
```swift
import UIKit
// MARK: - PinLockProgressView
//
final class PinLockProgressView: UIStackView {
/// Length of the progress view
///
var length: Int = 0 {
didSet {
configure()
}
}
/// Progress is from 0 to `length`
///
var progress: Int = 0 {
didSet {
guard oldValue != progress else {
return
}
progress = min(progress, length)
update()
}
}
override init(frame: CGRect) {
super.init(frame: frame)
configure()
}
required init(coder: NSCoder) {
super.init(coder: coder)
configure()
}
}
// MARK: - Private
//
private extension PinLockProgressView {
func configure() {
for view in arrangedSubviews {
removeArrangedSubview(view)
}
for _ in 0..<length {
let button = RoundedButton()
button.translatesAutoresizingMaskIntoConstraints = false
button.isUserInteractionEnabled = false
button.isAccessibilityElement = false
button.setBackgroundImage(UIColor.clear.dynamicImageRepresentation(), for: .normal)
button.setBackgroundImage(UIColor.white.dynamicImageRepresentation(), for: .highlighted)
button.layer.borderWidth = Constants.buttonBorderWidth
button.layer.borderColor = UIColor.white.cgColor
NSLayoutConstraint.activate([
button.widthAnchor.constraint(equalToConstant: Constants.buttonSideSize),
button.heightAnchor.constraint(equalToConstant: Constants.buttonSideSize)
])
addArrangedSubview(button)
}
}
func update() {
for (i, button) in arrangedSubviews.enumerated() {
(button as? UIButton)?.isHighlighted = i < progress
}
}
}
// MARK: - Constants
//
private enum Constants {
static let buttonBorderWidth: CGFloat = 1.0
static let buttonSideSize: CGFloat = 14.0
}
``` | /content/code_sandbox/Simplenote/PinLockProgressView.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 392 |
```swift
/// Simplenote API Credentials
///
@objcMembers
class SPCredentials: NSObject {
/// AppBot
///
static let appbotKey = "not-required"
/// AppCenter
///
static let appCenterIdentifier = "not-required"
/// Google Analytics
///
static let googleAnalyticsID = "not-required"
/// iTunes
///
static let iTunesAppID = "not-required"
static let iTunesReviewURL = URL(string: "path_to_url")!
/// Sentry
///
static let sentryDSN = "path_to_url"
/// Simperium: Credentials
///
static let simperiumAppID = "history-analyst-dad"
static let simperiumApiKey = "6805ca9a091e45ada8a9d8988367f14e"
/// Simperium: Reserved Object Keys
///
static let simperiumEmailVerificationObjectKey = "not-required"
static let simperiumPreferencesObjectKey = "not-required"
static let simperiumSettingsObjectKey = "not-required"
/// Simperium: Endpoints
///
static let defaultEngineURL = "path_to_url"
/// Simplenote's Send Feedback
///
static let simplenoteFeedbackURL = URL(string: "path_to_url")!
static let simplenoteFeedbackMail = "not.required@not.required.com"
/// WordPressSSO
///
static let wpcomClientID = "not-required"
static let wpcomRedirectURL = "not-required"
}
``` | /content/code_sandbox/Simplenote/SPCredentials-demo.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 339 |
```swift
import UIKit
// MARK: - SPSnappingSlider - Slider that snaps to certain values
//
@IBDesignable
final class SPSnappingSlider: UISlider {
/// Step for snapping
///
@IBInspectable
var step: Float = 1.0 {
didSet {
setValue(value, animated: false)
}
}
/// Callback to be executed when snapped value is updated
///
var onSnappedValueChange: ((Float) -> Void)?
/// Feedback generator is used to notify the user about changes in selection
///
private var feedbackGenerator: UISelectionFeedbackGenerator?
override init(frame: CGRect) {
super.init(frame: frame)
configure()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
configure()
}
/// Set and snap a value according to the step
///
override func setValue(_ value: Float, animated: Bool) {
let oldValue = self.value
var value = max(value, minimumValue)
value = min(value, maximumValue)
value = round(value / step) * step
super.setValue(value, animated: animated)
if oldValue != value {
feedbackGenerator?.selectionChanged()
onSnappedValueChange?(value)
}
}
}
// MARK: - Private Methods
//
private extension SPSnappingSlider {
func configure() {
configureFeedbackGenerator()
}
func configureFeedbackGenerator() {
feedbackGenerator = UISelectionFeedbackGenerator()
feedbackGenerator?.prepare()
}
}
// MARK: - Accessibility
extension SPSnappingSlider {
override func accessibilityIncrement() {
setValue(value + step, animated: true)
}
override func accessibilityDecrement() {
setValue(value - step, animated: true)
}
}
``` | /content/code_sandbox/Simplenote/SPSnappingSlider.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 381 |
```swift
import Foundation
extension URL {
static func internalUrl(forTag tag: String?) -> URL {
guard var components = URLComponents.simplenoteURLComponents(with: SimplenoteConstants.simplenoteInternalTagHost),
let tag = tag else {
return URL(string: .simplenotePath(withHost: SimplenoteConstants.simplenoteInternalTagHost))!
}
components.queryItems = [
URLQueryItem(name: Constants.tagQueryBase, value: tag)
]
return components.url!
}
static func newNoteURL(withTag tag: String? = nil) -> URL {
guard var components = URLComponents.simplenoteURLComponents(with: Constants.widgetNewNotePath) else {
return URL(string: .simplenotePath())!
}
if let tag = tag {
components.queryItems = [
URLQueryItem(name: Constants.tagQueryBase, value: tag)
]
}
return components.url!
}
static func newNoteWidgetURL() -> URL {
guard let components = URLComponents.simplenoteURLComponents(with: Constants.newNotePath) else {
return URL(string: .simplenotePath())!
}
return components.url!
}
}
private struct Constants {
static let tagQueryBase = "tag"
static let newNotePath = "new"
static let widgetNewNotePath = "widgetNew"
}
``` | /content/code_sandbox/Simplenote/URL+Simplenote.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 302 |
```swift
import UIKit
class SPDragBar: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
configure()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
configure()
}
private func configure() {
let color = UIColor(lightColor: ColorStudio.black, darkColor: ColorStudio.white)
backgroundColor = color
alpha = 0.2
layer.cornerRadius = 2.5
layer.masksToBounds = true
isAccessibilityElement = true
}
}
``` | /content/code_sandbox/Simplenote/SPDragBar.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 115 |
```swift
import UIKit
// MARK: - PopoverPresenter
//
final class PopoverPresenter {
private var popoverController: PopoverViewController?
private let containerViewController: UIViewController
private let siblingView: UIView?
private let viewportProvider: () -> CGRect
private var desiredHeight: CGFloat?
/// Is presented?
///
var isPresented: Bool {
return popoverController != nil
}
/// Should popover be dismissed when user interacts with passthru view
///
var dismissOnInteractionWithPassthruView: Bool = false
/// Dismiss on container frame change
///
var dismissOnContainerFrameChange: Bool = false
/// Center content relative to anchor
///
var centerContentRelativeToAnchor: Bool = false
/// Init
///
init(containerViewController: UIViewController,
viewportProvider: @escaping () -> CGRect,
siblingView: UIView? = nil) {
self.containerViewController = containerViewController
self.viewportProvider = viewportProvider
self.siblingView = siblingView
}
/// Show view controller as a popover around anchor
///
func show(_ viewController: UIViewController, around anchorInWindow: CGRect, desiredHeight: CGFloat? = nil) {
dismiss()
self.desiredHeight = desiredHeight
popoverController = PopoverViewController(viewController: viewController)
popoverController?.onInteractionWithPassthruView = { [weak self] in
if self?.dismissOnInteractionWithPassthruView == true {
self?.dismiss()
}
}
popoverController?.onViewSizeChange = { [weak self] in
if self?.dismissOnContainerFrameChange == true {
self?.dismiss()
}
}
popoverController?.attach(to: containerViewController,
attachmentView: siblingView.map({ .below($0) }),
animated: true)
relocate(around: anchorInWindow)
}
/// Relocates the receiver so that it shows up **around** the specified Anchor Frame
/// - Important: Frame must be expressed in Window Coordinates. Capisce?
///
func relocate(around anchorInWindow: CGRect) {
guard let popoverController = popoverController, let view = popoverController.view else {
return
}
let anchor = view.convert(anchorInWindow, from: nil)
let viewport = view.convert(viewportProvider(), from: nil)
let (orientation, viewportSlice) = calculateViewportSlice(around: anchor, in: viewport)
let height = calculateHeight(viewport: viewportSlice)
let leftLocation = calculateLeftLocation(around: anchor, in: viewport)
popoverController.containerMaxHeightConstraint.constant = height
popoverController.containerLeftConstraint.constant = leftLocation
popoverController.containerTopToTopConstraint.isActive = false
popoverController.containerTopToBottomConstraint.isActive = false
switch orientation {
case .above:
popoverController.containerTopToBottomConstraint.constant = anchor.minY - Metrics.defaultContentInsets.top
popoverController.containerTopToBottomConstraint.isActive = true
case .below:
popoverController.containerTopToTopConstraint.constant = anchor.maxY + Metrics.defaultContentInsets.top
popoverController.containerTopToTopConstraint.isActive = true
}
}
/// Adjusts the View by the specified offset
///
func relocate(by deltaY: CGFloat) {
popoverController?.containerTopToTopConstraint.constant += deltaY
popoverController?.containerTopToBottomConstraint.constant += deltaY
}
func dismiss() {
popoverController?.detach(animated: true)
popoverController = nil
}
}
// MARK: - Geometry
//
private extension PopoverPresenter {
/// Returns the Target Origin.X
///
/// - Parameters:
/// - anchor: Frame around which we should position the TableView
/// - viewport: Editor's visible frame
///
/// - Note: We'll align the Table **Text**, horizontally, with regards of the anchor frame. That's why we consider layout margins!
/// - Important: Whenever we overflow horizontally, we'll simply ensure there's enough breathing room on the right hand side
///
func calculateLeftLocation(around anchor: CGRect, in viewport: CGRect) -> CGFloat {
if centerContentRelativeToAnchor {
return anchor.midX - Metrics.defaultContentWidth / 2.0
}
let maximumX = anchor.minX + Metrics.defaultContentWidth + containerViewController.view.layoutMargins.right
if viewport.width > maximumX {
return anchor.minX - containerViewController.view.layoutMargins.left
}
return anchor.minX + viewport.width - maximumX
}
/// We'll always prefer displaying the Autocomplete UI **above** the cursor, whenever such location does not produce clipping.
/// Even if there's more room at the bottom (that's why a simple max calculation isn't enough!)
///
/// - Important: In order to avoid flipping Up / Down, we'll consider the Maximum Heigh tour TableView can acquire
///
func calculateViewportSlice(around anchor: CGRect, in viewport: CGRect) -> (Orientation, CGRect) {
let (viewportBelow, viewportAbove) = viewport.split(by: anchor)
guard let desiredHeight = desiredHeight else {
if viewportAbove.height > viewportBelow.height {
return (.above, viewportAbove)
}
return (.below, viewportBelow)
}
let deltaAbove = viewportAbove.height - desiredHeight
let deltaBelow = viewportBelow.height - desiredHeight
if (deltaAbove >= .zero) || (deltaAbove < .zero && deltaBelow < .zero && deltaAbove > deltaBelow) {
return (.above, viewportAbove)
}
return (.below, viewportBelow)
}
/// Returns the target Size.Height for the specified viewport metrics
///
func calculateHeight(viewport: CGRect) -> CGFloat {
let availableHeight = viewport.height - Metrics.defaultContentInsets.top - Metrics.defaultContentInsets.bottom
return max(availableHeight, Metrics.minimumHeight)
}
}
// MARK: - Defines the vertical orientation in which we'll display Popover
//
private enum Orientation {
case above
case below
}
// MARK: - Metrics
//
private enum Metrics {
static let defaultContentInsets = UIEdgeInsets(top: 12, left: 20, bottom: 12, right: 20)
static let defaultContentWidth = CGFloat(300)
static let minimumHeight = CGFloat(30)
}
``` | /content/code_sandbox/Simplenote/PopoverPresenter.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 1,362 |
```objective-c
#import "NSMutableAttributedString+Styling.h"
#import "NSString+Bullets.h"
#import "Simplenote-Swift.h"
@implementation NSMutableAttributedString (Checklists)
- (void)processChecklistsWithColor:(UIColor *)color
sizingFont:(UIFont *)sizingFont
allowsMultiplePerLine:(BOOL)allowsMultiplePerLine
{
if (self.length == 0) {
return;
}
NSString *plainString = [self.string copy];
NSRegularExpression *regex = allowsMultiplePerLine ? NSRegularExpression.regexForChecklistsEmbeddedAnywhere : NSRegularExpression.regexForChecklists;
NSArray *matches = [[[regex matchesInString:plainString
options:0
range:plainString.fullRange] reverseObjectEnumerator] allObjects];
for (NSTextCheckingResult *match in matches) {
if (NSRegularExpression.regexForChecklistsExpectedNumberOfRanges != match.numberOfRanges) {
continue;
}
NSRange matchedRange = [match rangeAtIndex:NSRegularExpression.regexForChecklistsMarkerRangeIndex];
if (matchedRange.location == NSNotFound || NSMaxRange(matchedRange) > self.length) {
continue;
}
NSString *matchedString = [plainString substringWithRange:matchedRange];
BOOL isChecked = [matchedString localizedCaseInsensitiveContainsString:@"x"];
SPTextAttachment *textAttachment = [SPTextAttachment new];
textAttachment.isChecked = isChecked;
textAttachment.tintColor = color;
textAttachment.sizingFont = sizingFont;
NSMutableAttributedString *attachmentString = [NSMutableAttributedString new];
if (allowsMultiplePerLine && matchedRange.location != 0) {
[attachmentString appendString:NSString.spaceString];
}
[attachmentString appendAttachment:textAttachment];
[self replaceCharactersInRange:matchedRange withAttributedString:attachmentString];
}
}
- (void)appendAttachment:(NSTextAttachment *)attachment
{
NSAttributedString *string = [NSAttributedString attributedStringWithAttachment:attachment];
[self appendAttributedString:string];
}
- (void)appendString:(NSString *)aString
{
NSAttributedString *string = [[NSAttributedString alloc] initWithString:aString];
[self appendAttributedString:string];
}
@end
``` | /content/code_sandbox/Simplenote/NSMutableAttributedString+Styling.m | objective-c | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 451 |
```objective-c
#import "SPAppDelegate.h"
#import "Simplenote-Swift.h"
#import "SPConstants.h"
#import "SPNavigationController.h"
#import "SPNoteListViewController.h"
#import "SPNoteEditorViewController.h"
#import "SPSettingsViewController.h"
#import "SPAddCollaboratorsViewController.h"
#import "NSManagedObjectContext+CoreDataExtensions.h"
#import "NSProcessInfo+Util.h"
#import "SPModalActivityIndicator.h"
#import "SPEditorTextView.h"
#import "SPObjectManager.h"
#import "Note.h"
#import "Tag.h"
#import "Settings.h"
#import "SPRatingsHelper.h"
#import "WPAuthHandler.h"
#import "SPTracker.h"
@import Contacts;
@import Simperium;
@class KeychainMigrator;
#if USE_APPCENTER
@import AppCenter;
@import AppCenterDistribute;
#endif
#pragma mark ================================================================================
#pragma mark Private Properties
#pragma mark ================================================================================
@interface SPAppDelegate ()
@property (weak, nonatomic) SPModalActivityIndicator *signOutActivityIndicator;
@end
#pragma mark ================================================================================
#pragma mark Simplenote AppDelegate
#pragma mark ================================================================================
@implementation SPAppDelegate
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
#pragma mark ================================================================================
#pragma mark Frameworks Setup
#pragma mark ================================================================================
- (void)authenticateSimperium
{
NSAssert(self.navigationController, nil);
[_simperium authenticateWithAppID:[SPCredentials simperiumAppID] APIKey:[SPCredentials simperiumApiKey] rootViewController:self.navigationController];
}
- (void)setupDefaultWindow
{
if (!self.window) {
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
}
self.window.backgroundColor = [UIColor simplenoteWindowBackgroundColor];
self.window.tintColor = [UIColor simplenoteTintColor];
self.tagListViewController = [TagListViewController new];
self.noteListViewController = [SPNoteListViewController new];
self.navigationController = [[SPNavigationController alloc] initWithRootViewController:_noteListViewController];
self.sidebarViewController = [[SPSidebarContainerViewController alloc] initWithMainViewController:self.navigationController
sidebarViewController:self.tagListViewController];
self.sidebarViewController.delegate = self.noteListViewController;
self.window.rootViewController = self.sidebarViewController;
[self.window makeKeyAndVisible];
}
- (void)setupAppCenter
{
#if USE_APPCENTER
NSLog(@"Initializing AppCenter...");
NSString *identifier = [SPCredentials appCenterIdentifier];
[MSACAppCenter start:identifier withServices:@[[MSACDistribute class]]];
[MSACDistribute setEnabled:true];
#endif
}
- (void)setupCrashLogging
{
[[CrashLogging shared] startWithSimperium: self.simperium];
}
- (void)setupThemeNotifications
{
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc addObserver:self selector:@selector(themeDidChange) name:SPSimplenoteThemeChangedNotification object:nil];
}
#pragma mark ================================================================================
#pragma mark AppDelegate Methods
#pragma mark ================================================================================
- (BOOL)application:(UIApplication *)application willFinishLaunchingWithOptions:(NSDictionary<UIApplicationLaunchOptionsKey,id> *)launchOptions
{
// Setup Frameworks
[self setupStorage];
[self setupThemeNotifications];
[self setupSimperium];
[self setupAuthenticator];
[self setupAppCenter];
[self setupCrashLogging];
[self configureVersionsController];
[self configurePublishController];
[self configureAccountDeletionController];
[self setupDefaultWindow];
[self configureStateRestoration];
[self migrateSimperiumPreferencesIfNeeded];
return YES;
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Once the UI is wired, Auth Simperium
[self authenticateSimperium];
// Start the StoreKit Manager
[self setupStoreManager];
// Handle Simplenote Migrations: We *need* to initialize the Ratings framework after this step, for reasons be.
[[MigrationsHandler new] ensureUpdateIsHandled];
[self setupAppRatings];
[[ShortcutsHandler shared] updateHomeScreenQuickActionsIfNeeded];
// Initialize UI
[self loadSelectedTheme];
// Check to see if first time user
if ([self isFirstLaunch]) {
_noteListViewController.firstLaunch = YES;
[[SPPinLockManager shared] removePin];
[self markFirstLaunch];
} else {
[self showPasscodeLockIfNecessary];
}
// Index (All of the) Spotlight Items if the user upgraded
[self indexSpotlightItemsIfNeeded];
[self setupNoticeController];
return YES;
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
[SPTracker trackApplicationOpened];
[self syncWidgetDefaults];
[self attemptContentRecoveryIfNeeded];
}
- (void)applicationDidEnterBackground:(UIApplication *)application
{
[SPTracker trackApplicationClosed];
// For the passcode lock, store the current clock time for comparison when returning to the app
if ([self.window isKeyWindow]) {
[[SPPinLockManager shared] storeLastUsedTime];
}
[self showPasscodeLockIfNecessary];
[self cleanupScrollPositionCache];
[self syncWidgetDefaults];
[self resetWidgetTimelines];
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
[self dismissPasscodeLockIfPossible];
[self authenticateSimperiumIfAccountDeletionRequested];
}
- (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void (^)(NSArray<id<UIUserActivityRestoring>> * _Nullable))restorationHandler
{
if ([self performMagicLinkAuthenticationWithUserActivity:userActivity]) {
return YES;
}
return [[ShortcutsHandler shared] handleUserActivity:userActivity];
}
- (void)application:(UIApplication *)application performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem completionHandler:(void (^)(BOOL))completionHandler
{
[[ShortcutsHandler shared] handleApplicationShortcut:shortcutItem];
}
- (void)applicationWillResignActive:(UIApplication *)application
{
UIViewController *viewController = self.window.rootViewController;
[viewController.view setNeedsLayout];
// Save any pending changes
[self.noteEditorViewController save];
}
- (void)applicationWillTerminate:(UIApplication *)application
{
// Save any pending changes
[self.noteEditorViewController save];
}
- (BOOL)application:(UIApplication *)application shouldSaveSecureApplicationState:(NSCoder *)coder
{
return YES;
}
- (BOOL)application:(UIApplication *)application shouldRestoreSecureApplicationState:(NSCoder *)coder
{
return YES;
}
#pragma mark - First Launch
- (BOOL)isFirstLaunch
{
return [[Options shared] firstLaunch] == NO;
}
- (void)markFirstLaunch
{
[[Options shared] setFirstLaunch:YES];
}
#pragma mark - Launch Helpers
- (void)loadSelectedTheme
{
[[SPUserInterface shared] refreshUserInterfaceStyle];
}
#pragma mark - Theme's
- (void)themeDidChange
{
self.window.backgroundColor = [UIColor simplenoteBackgroundColor];
self.window.tintColor = [UIColor simplenoteTintColor];
}
#pragma mark ================================================================================
#pragma mark Other
#pragma mark ================================================================================
- (void)presentSettingsViewController
{
SPSettingsViewController *settingsViewController = [SPSettingsViewController new];
SPNavigationController *navController = [[SPNavigationController alloc] initWithRootViewController:settingsViewController];
navController.disableRotation = YES;
navController.displaysBlurEffect = YES;
navController.modalPresentationStyle = UIModalPresentationFormSheet;
navController.modalPresentationCapturesStatusBarAppearance = YES;
[self.sidebarViewController presentViewController:navController animated:YES completion:nil];
}
- (void)logoutAndReset:(id)sender
{
self.bSigningUserOut = YES;
[self dismissAllModalsAnimated:YES completion:nil];
self.signOutActivityIndicator = [SPModalActivityIndicator showInWindow:self.window];
// Reset State
[SPKeychain deletePasswordForService:kSimplenoteWPServiceName account:self.simperium.user.email];
[[ShortcutsHandler shared] unregisterSimplenoteActivities];
[self.accountDeletionController clearRequestToken];
// Actual Simperium Logout
double delayInSeconds = 0.75;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
[self.simperium signOutAndRemoveLocalData:YES completion:^{
[self.navigationController popToRootViewControllerAnimated:YES];
self.selectedTag = nil;
[self.noteListViewController update];
[[CSSearchableIndex defaultSearchableIndex] deleteAllSearchableItemsWithCompletionHandler:nil];
// Nuke all of the User Preferences
[[Options shared] reset];
// remove the pin lock
[[SPPinLockManager shared] removePin];
// hide sidebar of notelist
[self.sidebarViewController hideSidebarWithAnimation:NO];
[self.signOutActivityIndicator dismiss:YES completion:nil];
[self.simperium authenticateIfNecessary];
self.bSigningUserOut = NO;
}];
});
}
- (void)save
{
[self.simperium save];
}
- (void)setSelectedTag:(NSString *)selectedTag {
BOOL tagsEqual = _selectedTag == selectedTag || (_selectedTag != nil && selectedTag != nil && [_selectedTag isEqual:selectedTag]);
if (tagsEqual) {
return;
}
_selectedTag = selectedTag;
[_noteListViewController update];
}
#pragma mark ================================================================================
#pragma mark SPBucket delegate
#pragma mark ================================================================================
- (void)bucket:(SPBucket *)bucket didChangeObjectForKey:(NSString *)key forChangeType:(SPBucketChangeType)change memberNames:(NSArray *)memberNames
{
if ([bucket isEqual:[_simperium notesBucket]]) {
// Note change
switch (change) {
case SPBucketChangeTypeUpdate:
{
if ([key isEqualToString:self.noteEditorViewController.note.simperiumKey]) {
[self.noteEditorViewController didReceiveNewContent];
NSString *deletedKey = NSStringFromSelector(@selector(deleted));
if (([memberNames.firstObject isEqualToString:deletedKey])) {
[self.noteEditorViewController didDeleteCurrentNote];
}
}
[self.publishController didReceiveUpdateNotificationForKey:key withMemberNames:memberNames];
Note *note = [bucket objectForKey:key];
if (note && !note.deleted) {
[[CSSearchableIndex defaultSearchableIndex] indexSearchableNote:note];
} else {
[[CSSearchableIndex defaultSearchableIndex] deleteSearchableItemsWithIdentifiers:@[key] completionHandler:nil];
}
}
break;
case SPBucketChangeTypeInsert:
break;
case SPBucketChangeTypeDelete:
{
if ([key isEqualToString:self.noteEditorViewController.note.simperiumKey]) {
[self.noteEditorViewController didDeleteCurrentNote];
}
[self.publishController didReceiveDeleteNotificationsForKey:key];
[[CSSearchableIndex defaultSearchableIndex] deleteSearchableItemsWithIdentifiers:@[key] completionHandler:nil];
}
break;
default:
break;
}
} else if ([bucket isEqual:[_simperium tagsBucket]]) {
// Tag deleted
switch (change) {
case SPBucketChangeTypeDelete:
{
// if selected tag is deleted, swap the note list view controller
if ([key isEqual:self.selectedTag]) {
self.selectedTag = nil;
}
break;
}
default:
break;
}
} else if ([bucket isEqual:[_simperium settingsBucket]]) {
[[SPRatingsHelper sharedInstance] reloadSettings];
} else if ([bucket isEqual:[_simperium accountBucket]] && [key isEqualToString:SPCredentials.simperiumEmailVerificationObjectKey]) {
[_verificationController updateWith:[bucket objectForKey:key]];
}
}
- (void)bucket:(SPBucket *)bucket willChangeObjectsForKeys:(NSSet *)keys
{
if ([bucket isEqual:[_simperium notesBucket]]) {
for (NSString *key in keys) {
if ([key isEqualToString:self.noteEditorViewController.note.simperiumKey]) {
[self.noteEditorViewController willReceiveNewContent];
}
}
}
}
- (void)bucket:(SPBucket *)bucket didReceiveObjectForKey:(NSString *)key version:(NSString *)version data:(NSDictionary *)data
{
if ([bucket isEqual:[_simperium notesBucket]]) {
[self.versionsController didReceiveObjectForSimperiumKey:key version:[version integerValue] data:data];
}
}
- (void)bucketWillStartIndexing:(SPBucket *)bucket
{
if ([bucket isEqual:[_simperium notesBucket]]) {
[_noteListViewController setWaitingForIndex:YES];
}
}
- (void)bucketDidFinishIndexing:(SPBucket *)bucket
{
if ([bucket isEqual:[_simperium notesBucket]]) {
[_noteListViewController setWaitingForIndex:NO];
[self indexSpotlightItems];
} else if ([bucket isEqual:[_simperium accountBucket]]) {
[_verificationController updateWith:[bucket objectForKey:SPCredentials.simperiumEmailVerificationObjectKey]];
}
}
#pragma mark ================================================================================
#pragma mark Spotlight
#pragma mark ================================================================================
- (void)indexSpotlightItemsIfNeeded
{
// This process should be executed *just once*, and only if the user is already logged in (AKA "Upgrade")
NSString *kSpotlightDidRunKey = @"SpotlightDidRunKey";
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if ([defaults boolForKey:kSpotlightDidRunKey] == true) {
return;
}
[defaults setBool:true forKey:kSpotlightDidRunKey];
[defaults synchronize];
if (self.simperium.user.authenticated == false) {
return;
}
[self indexSpotlightItems];
}
- (void)indexSpotlightItems
{
NSManagedObjectContext *context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
[context setParentContext:self.simperium.managedObjectContext];
[[CSSearchableIndex defaultSearchableIndex] indexSpotlightItemsIn:context];
}
#pragma mark ================================================================================
#pragma mark URL scheme
#pragma mark ================================================================================
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options
{
if (!self.simperium.user.authenticated) {
[self performDotcomAuthenticationWithURL:url];
if (!self.simperium.user.authenticated && url) {
[self performMagicLinkAuthenticationWith:url];
}
return YES;
}
// URL: Open a Note!
if ([self handleOpenNoteWithUrl:url]) {
return YES;
}
if ([self handleOpenTagListWithUrl:url]) {
return YES;
}
// Support opening Simplenote and optionally creating a new note
NSURLComponents *components = [NSURLComponents componentsWithURL:url resolvingAgainstBaseURL:NO];
if ([[components host] isEqualToString:@"new"]) {
Note *newNote = [[SPObjectManager sharedManager] newNoteWithContent:[components contentFromQuery] tags:[components tagsFromQuery]];
[self presentNote:newNote animated:NO];
}
if ([[components host] isEqualToString:@"widgetNew"]) {
[self presentNewNoteEditorWithUseSelectedTag:NO animated:NO];
}
return YES;
}
- (void)performDotcomAuthenticationWithURL:(NSURL *)url
{
if (![WPAuthHandler isWPAuthenticationUrl:url]) {
return;
}
SPUser *user = [WPAuthHandler authorizeSimplenoteUserFromUrl:url forAppId:[SPCredentials simperiumAppID]];
if (user == nil) {
return;
}
self.simperium.user = user;
[self.navigationController dismissViewControllerAnimated:YES completion:nil];
[self.simperium authenticationDidSucceedForUsername:user.email token:user.authToken];
[SPTracker trackWPCCLoginSucceeded];
}
#pragma mark ================================================================================
#pragma mark App Tracking
#pragma mark ================================================================================
- (void)setupAppRatings
{
// Dont start App Tracking if we are running the test suite
if ([NSProcessInfo isRunningTests]) {
return;
}
NSString *version = [[NSBundle mainBundle] shortVersionString];
[[SPRatingsHelper sharedInstance] initializeForVersion:version];
[[SPRatingsHelper sharedInstance] reloadSettings];
}
#pragma mark ================================================================================
#pragma mark Static Helpers
#pragma mark ================================================================================
+ (SPAppDelegate *)sharedDelegate
{
return (SPAppDelegate *)[[UIApplication sharedApplication] delegate];
}
@end
``` | /content/code_sandbox/Simplenote/SPAppDelegate.m | objective-c | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 3,567 |
```swift
import Foundation
extension UIButton {
func setTitleWithoutAnimation(_ title: String?, for state: UIControl.State) {
UIView.performWithoutAnimation {
self.setTitle(title, for: state)
self.layoutIfNeeded()
}
}
func setAttributedTitleWithoutAnimation(_ title: NSAttributedString?, for state: UIControl.State) {
UIView.performWithoutAnimation {
self.setAttributedTitle(title, for: state)
self.layoutIfNeeded()
}
}
}
``` | /content/code_sandbox/Simplenote/UIButton+Simplenote.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 98 |
```swift
import Foundation
// MARK: - Note + Links
//
extension Note {
/// Internal note link
///
var plainInternalLink: String? {
guard let key = simperiumKey else {
return nil
}
return .simplenotePath(withHost: SimplenoteConstants.simplenoteInterlinkHost) + key
}
/// Returns the receiver's Markdown Internal Reference, when possible
///
var markdownInternalLink: String? {
guard let title = titlePreview, let plainInternalLink = plainInternalLink else {
return nil
}
let shortened = title.truncateWords(upTo: SimplenoteConstants.simplenoteInterlinkMaxTitleLength)
return "[" + shortened + "](" + plainInternalLink + ")"
}
/// Returns the full Public Link to the current document
///
@objc
var publicLink: String? {
guard let targetURL = publishURL, targetURL.isEmpty == false, published else {
return nil
}
return SimplenoteConstants.simplenotePublishedBaseURL + targetURL
}
func instancesOfReference(to note: Note) -> Int {
guard let internalLink = note.plainInternalLink else {
return .zero
}
return content.occurrences(of: internalLink)
}
}
``` | /content/code_sandbox/Simplenote/Note+Links.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 283 |
```objective-c
//
// SPConstants.m
// Simplenote
//
// Created by Jorge Leandro Perez on 12/22/14.
//
#import "SPConstants.h"
#pragma mark ================================================================================
#pragma mark Constants
#pragma mark ================================================================================
NSString *const kSimperiumBaseURL = @"path_to_url";
NSString *const kSimperiumForgotPasswordURL = @"path_to_url";
NSString *const kSimperiumTermsOfServiceURL = @"path_to_url";
NSString *const kSimperiumPreferencesObjectKey = @"preferences-key";
NSString *const kAutomatticAnalyticLearnMoreURL = @"path_to_url";
#ifdef APPSTORE_DISTRIBUTION
NSString *const kShareExtensionGroupName = @"group.com.codality.NotationalFlow";
#elif INTERNAL_DISTRIBUTION
NSString *const kShareExtensionGroupName = @"group.com.codality.NotationalFlow.Internal";
#elif RELEASE
NSString *const kShareExtensionGroupName = @"group.com.codality.NotationalFlow";
#else
NSString *const kShareExtensionGroupName = @"group.com.codality.NotationalFlow.Development";
#endif
NSString *const kSimplenoteTrashKey = @"__##__trash__##__";
NSString *const kSimplenoteUntaggedKey = @"__##__untagged__##__";
NSString *const kSimplenoteWPServiceName = @"simplenote-wpcom";
NSString *const kSignInErrorNotificationName = @"SPSignInErrorNotificationName";
NSString *const kPinTimeoutPreferencesKey = @"kPinTimeoutPreferencesKey";
NSString *const kWordPressAuthURL = @"path_to_url";
``` | /content/code_sandbox/Simplenote/SPConstants.m | objective-c | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 346 |
```swift
import UIKit
// MARK: - SubtitleTableViewCell
//
final class SubtitleTableViewCell: UITableViewCell {
/// Wraps the TextLabel's Text Property
///
var title: String? {
get {
textLabel?.text
}
set {
textLabel?.text = newValue
}
}
/// Wraps the DetailTextLabel's Text Property
///
var value: String? {
get {
detailTextLabel?.text
}
set {
detailTextLabel?.text = newValue
}
}
// MARK: - Initializers
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: .subtitle, reuseIdentifier: reuseIdentifier)
reloadBackgroundStyles()
reloadTextStyles()
}
required init?(coder: NSCoder) {
fatalError("Unsupported Initializer")
}
// MARK: - Overriden
override func prepareForReuse() {
super.prepareForReuse()
accessoryType = .none
}
}
// MARK: - Private API(s)
//
private extension SubtitleTableViewCell {
func reloadBackgroundStyles() {
let selectedView = UIView(frame: bounds)
selectedView.backgroundColor = .simplenoteLightBlueColor
backgroundColor = .clear
selectedBackgroundView = selectedView
}
func reloadTextStyles() {
let textColor: UIColor = .simplenoteTextColor
let detailTextColor: UIColor = .simplenoteSecondaryTextColor
textLabel?.textColor = textColor
detailTextLabel?.textColor = detailTextColor
textLabel?.font = UIFont.preferredFont(for: .body, weight: .regular)
detailTextLabel?.font = UIFont.preferredFont(for: .subheadline, weight: .regular)
}
}
``` | /content/code_sandbox/Simplenote/SubtitleTableViewCell.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 370 |
```swift
import UIKit
// MARK: - SPTextAttachment
//
@objcMembers
class SPTextAttachment: NSTextAttachment {
/// Extra Sizing Points to be appled over the actual Sizing Font Size
///
var extraDimensionPoints: CGFloat = 4
/// Indicates if we're in the Checked or Unchecked state
///
var isChecked = false {
didSet {
refreshImage()
}
}
/// Updates the Attachment's Tint Color
///
var tintColor: UIColor? {
didSet {
refreshImage()
}
}
/// Font to be used for Attachment Sizing purposes
///
var sizingFont: UIFont = .preferredFont(forTextStyle: .headline)
// MARK: - Overridden Methods
override func attachmentBounds(for textContainer: NSTextContainer?, proposedLineFragment lineFrag: CGRect, glyphPosition position: CGPoint, characterIndex charIndex: Int) -> CGRect {
let dimension = sizingFont.pointSize + extraDimensionPoints
let offsetY = round((sizingFont.capHeight - dimension) * 0.5)
return CGRect(x: 0, y: offsetY, width: dimension, height: dimension)
}
}
// MARK: - Private
//
private extension SPTextAttachment {
func refreshImage() {
guard let tintColor = tintColor else {
return
}
let name: UIImageName = isChecked ? .taskChecked : .taskUnchecked
image = UIImage.image(name: name)?.withOverlayColor(tintColor)
}
}
``` | /content/code_sandbox/Simplenote/SPTextAttachment.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 323 |
```swift
import Foundation
// MARK: - SPNoteHistoryControllerDelegate
//
protocol SPNoteHistoryControllerDelegate: AnyObject {
/// Cancel
///
func noteHistoryControllerDidCancel()
/// Finish and save
///
func noteHistoryControllerDidFinish()
/// Preview version content
///
func noteHistoryControllerDidSelectVersion(withContent content: String)
}
``` | /content/code_sandbox/Simplenote/SPNoteHistoryControllerDelegate.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 77 |
```swift
import Foundation
// MARK: - UIAlertController Helpers
//
extension UIAlertController {
/// Builds an alert indicating that the Login Code has Expired
///
static func buildLoginCodeNotFoundAlert(onRequestCode: @escaping () -> Void) -> UIAlertController {
let title = NSLocalizedString("Sorry!", comment: "Email TextField Placeholder")
let message = NSLocalizedString("The authentication code you've requested has expired. Please request a new one", comment: "Email TextField Placeholder")
let acceptText = NSLocalizedString("Accept", comment: "Accept Message")
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
alertController.addDefaultActionWithTitle(acceptText) { _ in
onRequestCode()
}
return alertController
}
}
``` | /content/code_sandbox/Simplenote/UIAlertController+Auth.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 157 |
```swift
import SwiftUI
extension Color {
/// Convenience initializers to get and use Simplenote color studio colors
///
init(studioColor: ColorStudio, alpha: CGFloat = UIKitConstants.alpha1_0) {
self.init(UIColor(studioColor: studioColor, alpha: alpha))
}
init(for colorScheme: ColorScheme, light: ColorStudio, lightAlpha: CGFloat = UIKitConstants.alpha1_0, dark: ColorStudio, darkAlpha: CGFloat = UIKitConstants.alpha1_0) {
let color = colorScheme == .dark ? dark : light
let alpha = colorScheme == .dark ? darkAlpha : lightAlpha
self.init(UIColor(studioColor: color, alpha: alpha))
}
init(light: ColorStudio, lightAlpha: CGFloat = UIKitConstants.alpha1_0, dark: ColorStudio, darkAlpha: CGFloat = UIKitConstants.alpha1_0) {
self.init(UIColor(lightColor: light, darkColor: dark, lightColorAlpha: lightAlpha, darkColorAlpha: darkAlpha))
}
}
``` | /content/code_sandbox/Simplenote/Color+Simplenote.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 224 |
```swift
import Foundation
// MARK: - SPCardConfigurable: configure card
//
protocol SPCardConfigurable {
/// This method allows the adopter to control swipe-to-dismiss
///
/// - Parameters:
/// - location: location in receiver's coordinate system.
///
/// - Returns: Boolean value indicating if dismiss should begin
///
func shouldBeginSwipeToDismiss(from location: CGPoint) -> Bool
}
``` | /content/code_sandbox/Simplenote/SPCardConfigurable.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 92 |
```swift
import UIKit
extension UIView {
struct EdgeConstraints {
let leading: NSLayoutConstraint
let trailing: NSLayoutConstraint
let top: NSLayoutConstraint
let bottom: NSLayoutConstraint
func update(with edgeInsets: UIEdgeInsets) {
leading.constant = edgeInsets.left
trailing.constant = -edgeInsets.right
top.constant = edgeInsets.top
bottom.constant = -edgeInsets.bottom
}
func activate() {
NSLayoutConstraint.activate([leading, trailing, top, bottom])
}
}
enum AnchorTarget {
case bounds
case safeArea
case layoutMargins
}
@discardableResult
func addFillingSubview(_ view: UIView,
edgeInsets: UIEdgeInsets = .zero,
target: AnchorTarget = .bounds) -> EdgeConstraints {
addSubview(view)
return pinSubviewToAllEdges(view, edgeInsets: edgeInsets, target: target)
}
@discardableResult
func pinSubviewToAllEdges(_ view: UIView, edgeInsets: UIEdgeInsets = .zero, target: AnchorTarget = .bounds) -> EdgeConstraints {
view.translatesAutoresizingMaskIntoConstraints = false
let layoutGuide: UILayoutGuide?
switch target {
case .bounds:
layoutGuide = nil
case .layoutMargins:
layoutGuide = layoutMarginsGuide
case .safeArea:
layoutGuide = safeAreaLayoutGuide
}
let constraints = EdgeConstraints(leading: view.leadingAnchor.constraint(equalTo: layoutGuide?.leadingAnchor ?? leadingAnchor),
trailing: view.trailingAnchor.constraint(equalTo: layoutGuide?.trailingAnchor ?? trailingAnchor),
top: view.topAnchor.constraint(equalTo: layoutGuide?.topAnchor ?? topAnchor),
bottom: view.bottomAnchor.constraint(equalTo: layoutGuide?.bottomAnchor ?? bottomAnchor))
constraints.update(with: edgeInsets)
constraints.activate()
return constraints
}
func pinSubviewToCenter(_ view: UIView) {
view.translatesAutoresizingMaskIntoConstraints = false
let constraints = [
view.centerXAnchor.constraint(equalTo: centerXAnchor),
view.centerYAnchor.constraint(equalTo: centerYAnchor)
]
NSLayoutConstraint.activate(constraints)
}
}
``` | /content/code_sandbox/Simplenote/UIView+Constraints.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 434 |
```swift
import UIKit
// MARK: - Card presentation animator
//
final class SPCardPresentationAnimator: NSObject, UIViewControllerAnimatedTransitioning {
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return UIKitConstants.animationShortDuration
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
guard let view = transitionContext.view(forKey: .to) else {
return
}
// layout to get correct view size
view.superview?.setNeedsLayout()
view.superview?.layoutIfNeeded()
view.transform = CGAffineTransform(translationX: 0.0, y: view.frame.size.height)
let animationBlock: () -> Void = {
view.transform = .identity
}
let animator = UIViewPropertyAnimator(duration: transitionDuration(using: transitionContext),
curve: .easeOut,
animations: animationBlock)
animator.addCompletion { (_) in
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
}
animator.startAnimation()
}
}
``` | /content/code_sandbox/Simplenote/SPCardPresentationAnimator.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 213 |
```swift
import UIKit
// MARK: - HuggableTableView
// Table View that wraps it's own content (tries to set it's own height to match the content)
//
class HuggableTableView: UITableView {
lazy var maxHeightConstraint: NSLayoutConstraint = {
let constraint = heightAnchor.constraint(lessThanOrEqualToConstant: CGFloat.greatestFiniteMagnitude)
constraint.priority = UILayoutPriority(rawValue: 999)
constraint.isActive = true
return constraint
}()
lazy var minHeightConstraint: NSLayoutConstraint = {
let constraint = heightAnchor.constraint(greaterThanOrEqualToConstant: 0)
constraint.priority = UILayoutPriority(rawValue: 999)
constraint.isActive = true
return constraint
}()
var maxNumberOfVisibleRows: CGFloat? {
didSet {
updateMaxHeightConstraint()
}
}
override var frame: CGRect {
didSet {
updateScrollState()
}
}
override var contentSize: CGSize {
didSet {
invalidateIntrinsicContentSize()
updateMaxHeightConstraint()
}
}
override func safeAreaInsetsDidChange() {
super.safeAreaInsetsDidChange()
invalidateIntrinsicContentSize()
}
override func invalidateIntrinsicContentSize() {
super.invalidateIntrinsicContentSize()
updateScrollState()
}
override var intrinsicContentSize: CGSize {
var size = contentSize
size.height += safeAreaInsets.top + safeAreaInsets.bottom
return size
}
private func updateScrollState() {
isScrollEnabled = frame.size.height < intrinsicContentSize.height
}
private func updateMaxHeightConstraint() {
if let numberOfRows = maxNumberOfVisibleRows {
maxHeightConstraint.constant = height(of: numberOfRows)
}
}
private func height(of numberOfRows: CGFloat) -> CGFloat {
let totalRows = dataSource?.tableView(self, numberOfRowsInSection: 0) ?? 0
let lastRow = min(Int(ceil(numberOfRows)), totalRows) - 1
guard lastRow >= 0 else {
return 0.0
}
let rect = rectForRow(at: IndexPath(row: lastRow, section: 0))
let fractionalPart = min(numberOfRows, CGFloat(totalRows)).truncatingRemainder(dividingBy: 1)
if fractionalPart > .leastNormalMagnitude {
return rect.minY + rect.height * fractionalPart
}
return rect.maxY
}
}
``` | /content/code_sandbox/Simplenote/HuggableTableView.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 500 |
```swift
import Foundation
// MARK: - NSPredicate Validation Methods
//
extension NSPredicate {
/// Returns a NSPredicate capable of validating Email Addressess
///
static func predicateForEmailValidation() -> NSPredicate {
let regex = ".+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2}[A-Za-z]*"
return NSPredicate(format: "SELF MATCHES %@", regex)
}
}
``` | /content/code_sandbox/Simplenote/NSPredicate+Email.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 91 |
```swift
import Foundation
// MARK: - State
//
struct AuthenticationState {
var username = String()
var password = String()
var code = String()
}
// MARK: - Authentication Elements
//
struct AuthenticationInputElements: OptionSet, Hashable {
let rawValue: UInt
static let username = AuthenticationInputElements(rawValue: 1 << 0)
static let password = AuthenticationInputElements(rawValue: 1 << 1)
static let code = AuthenticationInputElements(rawValue: 1 << 2)
static let actionSeparator = AuthenticationInputElements(rawValue: 1 << 3)
}
// MARK: - Authentication Actions
//
enum AuthenticationActionName {
case primary
case secondary
case tertiary
case quaternary
}
struct AuthenticationActionDescriptor {
let name: AuthenticationActionName
let selector: Selector
let text: String?
let attributedText: NSAttributedString?
init(name: AuthenticationActionName, selector: Selector, text: String?, attributedText: NSAttributedString? = nil) {
self.name = name
self.selector = selector
self.text = text
self.attributedText = attributedText
}
}
// MARK: - AuthenticationMode: Signup / Login
//
struct AuthenticationMode {
let title: String
let header: String?
let inputElements: AuthenticationInputElements
let validationStyle: AuthenticationValidator.Style
let actions: [AuthenticationActionDescriptor]
init(title: String, header: String? = nil, inputElements: AuthenticationInputElements, validationStyle: AuthenticationValidator.Style, actions: [AuthenticationActionDescriptor]) {
self.title = title
self.header = header
self.inputElements = inputElements
self.validationStyle = validationStyle
self.actions = actions
}
}
// MARK: - Public Properties
//
extension AuthenticationMode {
func buildHeaderText(email: String) -> NSAttributedString? {
guard let header = header?.replacingOccurrences(of: "{{EMAIL}}", with: email) else {
return nil
}
return NSMutableAttributedString(string: header, attributes: [
.font: UIFont.preferredFont(for: .headline, weight: .regular)
], highlighting: email, highlightAttributes: [
.font: UIFont.preferredFont(for: .headline, weight: .bold)
])
}
}
// MARK: - Default Operation Modes
//
extension AuthenticationMode {
/// Login with Password
///
static func loginWithPassword(header: String? = nil) -> AuthenticationMode {
return .init(title: NSLocalizedString("Log In with Password", comment: "LogIn Interface Title"),
header: header,
inputElements: [.password],
validationStyle: .legacy,
actions: [
AuthenticationActionDescriptor(name: .primary,
selector: #selector(SPAuthViewController.performLogInWithPassword),
text: NSLocalizedString("Log In", comment: "LogIn Action")),
AuthenticationActionDescriptor(name: .secondary,
selector: #selector(SPAuthViewController.presentPasswordReset),
text: NSLocalizedString("Forgot your password?", comment: "Password Reset Action"))
])
}
/// Requests a Login Code
///
static var requestLoginCode: AuthenticationMode {
return .init(title: NSLocalizedString("Log In", comment: "LogIn Interface Title"),
inputElements: [.username, .actionSeparator],
validationStyle: .legacy,
actions: [
AuthenticationActionDescriptor(name: .primary,
selector: #selector(SPAuthViewController.requestLogInCode),
text: NSLocalizedString("Log in with email", comment: "Sends the User an email with an Authentication Code")),
AuthenticationActionDescriptor(name: .tertiary,
selector: #selector(SPAuthViewController.performLogInWithWPCOM),
text: NSLocalizedString("Log in with WordPress.com", comment: "Password fallback Action"))
])
}
/// Login with Code: Submit Code + Authenticate the user
///
static var loginWithCode: AuthenticationMode {
return .init(title: NSLocalizedString("Enter Code", comment: "LogIn Interface Title"),
header: NSLocalizedString("We've sent a code to {{EMAIL}}. The code will be valid for a few minutes.", comment: "Header for the Login with Code UI. Please preserve the {{EMAIL}} string as is!"),
inputElements: [.code, .actionSeparator],
validationStyle: .legacy,
actions: [
AuthenticationActionDescriptor(name: .primary,
selector: #selector(SPAuthViewController.performLogInWithCode),
text: NSLocalizedString("Log In", comment: "LogIn Interface Title")),
AuthenticationActionDescriptor(name: .quaternary,
selector: #selector(SPAuthViewController.presentPasswordInterface),
text: NSLocalizedString("Enter password", comment: "Enter Password fallback Action")),
])
}
/// Signup: Contains all of the strings + delegate wirings, so that the AuthUI handles user account creation scenarios.
///
static var signup: AuthenticationMode {
return .init(title: NSLocalizedString("Sign Up", comment: "SignUp Interface Title"),
inputElements: [.username],
validationStyle: .strong,
actions: [
AuthenticationActionDescriptor(name: .primary,
selector: #selector(SPAuthViewController.performSignUp),
text: NSLocalizedString("Sign Up", comment: "SignUp Action")),
AuthenticationActionDescriptor(name: .secondary,
selector: #selector(SPAuthViewController.presentTermsOfService),
text: nil,
attributedText: SignupStrings.termsOfService)
])
}
}
// MARK: - Mode: .signup
//
private enum SignupStrings {
/// Returns a formatted Secondary Action String for Signup
///
static var termsOfService: NSAttributedString {
let output = NSMutableAttributedString(string: String(), attributes: [
.font: UIFont.preferredFont(forTextStyle: .subheadline)
])
let prefix = NSLocalizedString("By creating an account you agree to our", comment: "Terms of Service Legend *PREFIX*: printed in dark color")
let suffix = NSLocalizedString("Terms and Conditions", comment: "Terms of Service Legend *SUFFIX*: Concatenated with a space, after the PREFIX, and printed in blue")
output.append(string: prefix, foregroundColor: .simplenoteGray60Color)
output.append(string: " ")
output.append(string: suffix, foregroundColor: .simplenoteBlue60Color)
return output
}
}
``` | /content/code_sandbox/Simplenote/AuthenticationMode.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 1,340 |
```swift
import Foundation
class TimerFactory {
func scheduledTimer(with timeInterval: TimeInterval, completion: @escaping () -> Void) -> Timer {
return Timer.scheduledTimer(withTimeInterval: timeInterval, repeats: false) { (_) in
completion()
}
}
func repeatingTimer(with timerInterval: TimeInterval, completion: @escaping (Timer)-> Void) -> Timer {
return Timer.scheduledTimer(withTimeInterval: timerInterval, repeats: true) { (timer) in
completion(timer)
}
}
}
``` | /content/code_sandbox/Simplenote/TimerFactory.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 109 |
```objective-c
#import <UIKit/UIKit.h>
#import <Simperium/Simperium.h>
@class SPSidebarContainerViewController;
@class TagListViewController;
@class SPNoteListViewController;
@class SPNoteEditorViewController;
@class SPNavigationController;
@class VersionsController;
@class AccountVerificationController;
@class AccountVerificationViewController;
@class PublishController;
@class PublishStateObserver;
@class AccountDeletionController;
@class CoreDataManager;
NS_ASSUME_NONNULL_BEGIN
@interface SPAppDelegate : UIResponder <UIApplicationDelegate, SPBucketDelegate>
@property (strong, nonatomic) UIWindow *window;
@property (nullable, strong, nonatomic) UIWindow *pinLockWindow;
@property (strong, nonatomic) Simperium *simperium;
@property (strong, nonatomic) CoreDataManager *coreDataManager;
@property (strong, nonatomic) SPSidebarContainerViewController *sidebarViewController;
@property (strong, nonatomic) TagListViewController *tagListViewController;
@property (strong, nonatomic) SPNoteListViewController *noteListViewController;
@property (strong, nonatomic) SPNavigationController *navigationController;
@property (strong, nonatomic) VersionsController *versionsController;
@property (strong, nonatomic) PublishController *publishController;
@property (weak, nonatomic) AccountVerificationViewController *verificationViewController;
@property (strong, nonatomic, nullable) AccountVerificationController *verificationController;
@property (nullable, strong, nonatomic) NSString *selectedTag;
@property (assign, nonatomic) BOOL bSigningUserOut;
@property (nullable, strong, nonatomic) AccountDeletionController *accountDeletionController;
- (void)presentSettingsViewController;
- (void)save;
- (void)logoutAndReset:(id)sender;
- (BOOL)isFirstLaunch;
+ (SPAppDelegate *)sharedDelegate;
@end
NS_ASSUME_NONNULL_END
``` | /content/code_sandbox/Simplenote/SPAppDelegate.h | objective-c | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 362 |
```swift
import UIKit
// MARK: - Search map view
//
@objc
final class SearchMapView: UIView {
/// Callback to be invoked on selection change
///
var onSelectionChange: ((Int) -> Void)?
private var barViews: [UIView] = []
private lazy var feedbackGenerator = UISelectionFeedbackGenerator()
private var lastSelectedIndex: Int? {
didSet {
guard oldValue != lastSelectedIndex, let index = lastSelectedIndex else {
return
}
feedbackGenerator.selectionChanged()
onSelectionChange?(index)
}
}
/// Constructor
///
override init(frame: CGRect) {
super.init(frame: frame)
isAccessibilityElement = false
translatesAutoresizingMaskIntoConstraints = false
prepareFeedbackGenerator()
setupGestureRecognizers()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/// Update with positions of bars. Position is from 0.0 to 1.0
///
func update(with positions: [CGFloat]) {
for barView in barViews {
barView.removeFromSuperview()
}
barViews = []
for position in positions {
createBarView(with: position)
}
}
private func createBarView(with position: CGFloat) {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = UIColor.simplenoteBlue50Color
addSubview(view)
let verticalCenterConstraint = NSLayoutConstraint(item: view,
attribute: .centerY,
relatedBy: .equal,
toItem: self,
attribute: .centerY,
multiplier: position * 2,
constant: 0.0)
verticalCenterConstraint.priority = .defaultHigh
NSLayoutConstraint.activate([
view.heightAnchor.constraint(equalToConstant: Metrics.barHeight),
view.leadingAnchor.constraint(equalTo: leadingAnchor),
view.trailingAnchor.constraint(equalTo: trailingAnchor),
view.topAnchor.constraint(greaterThanOrEqualTo: topAnchor),
view.bottomAnchor.constraint(lessThanOrEqualTo: bottomAnchor),
verticalCenterConstraint
])
barViews.append(view)
}
}
// MARK: - Configuration
//
private extension SearchMapView {
func prepareFeedbackGenerator() {
feedbackGenerator.prepare()
}
func setupGestureRecognizers() {
let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(handleGesture(_:)))
addGestureRecognizer(panGestureRecognizer)
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleGesture(_:)))
addGestureRecognizer(tapGestureRecognizer)
}
}
// MARK: - Handling Gestures
//
private extension SearchMapView {
@objc
func handleGesture(_ gestureRecognizer: UIGestureRecognizer) {
switch gestureRecognizer.state {
case .began, .changed, .ended:
let location = gestureRecognizer.location(in: self)
guard let selectedView = barView(with: location) else {
lastSelectedIndex = nil
return
}
lastSelectedIndex = barViews.firstIndex(of: selectedView)
// reset after a tap
if gestureRecognizer.state == .ended {
lastSelectedIndex = nil
}
default:
lastSelectedIndex = nil
}
}
}
// MARK: - Hit testing
//
extension SearchMapView {
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
return barView(with: point)
}
private func barView(with point: CGPoint) -> UIView? {
return barViews.filter {
$0.frame.insetBy(dx: -Metrics.extraHorizontalTouchMargin, dy: -Metrics.extraVerticalTouchMargin).contains(point)
}.sorted {
let distance1 = abs($0.frame.midY - point.y)
let distance2 = abs($1.frame.midY - point.y)
return distance1 < distance2
}.first
}
}
private enum Metrics {
static let barHeight: CGFloat = 4.0
static let extraHorizontalTouchMargin: CGFloat = 10
static let extraVerticalTouchMargin: CGFloat = 10
}
``` | /content/code_sandbox/Simplenote/SearchMapView.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 848 |
```swift
import Foundation
import SwiftUI
import Gridicons
// MARK: - MagicLinkRequestedView
//
struct MagicLinkRequestedView: View {
@Environment(\.presentationMode) var presentationMode
@State private var displaysFullImage: Bool = false
let email: String
var body: some View {
NavigationView {
VStack(alignment: .center, spacing: 10) {
Image(uiImage: MagicLinkImages.mail)
.renderingMode(.template)
.foregroundColor(Color(.simplenoteBlue60Color))
.scaleEffect(displaysFullImage ? 1 : 0.4)
.onAppear {
withAnimation(.spring(response: 0.3, dampingFraction: 0.3)) {
displaysFullImage = true
}
}
Text("Check your email")
.bold()
.font(.system(size: Metrics.titleFontSize))
Spacer()
.frame(height: Metrics.titlePaddingBottom)
Text("If an account exists, we've sent an email with a link that'll log you in to **\(email)**")
.font(.system(size: Metrics.detailsFontSize))
.multilineTextAlignment(.center)
}
.padding()
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
Button(action: {
presentationMode.wrappedValue.dismiss()
}) {
Image(uiImage: MagicLinkImages.dismiss)
.renderingMode(.template)
.foregroundColor(Color(.darkGray))
}
}
}
}
.navigationViewStyle(.stack)
/// Force Light Mode (since the Authentication UI is all light!)
.environment(\.colorScheme, .light)
}
}
// MARK: - Constants
//
private enum Metrics {
static let titleFontSize: CGFloat = 22
static let titlePaddingBottom: CGFloat = 10
static let detailsFontSize: CGFloat = 17
static let mailIconSize = CGSize(width: 100, height: 100)
static let dismissSize = CGSize(width: 30, height: 30)
}
private enum MagicLinkImages {
static let mail = Gridicon.iconOfType(.mail, withSize: Metrics.mailIconSize)
static let dismiss = Gridicon.iconOfType(.crossCircle, withSize: Metrics.dismissSize)
}
struct MagicLinkRequestedView_Previews: PreviewProvider {
static var previews: some View {
MagicLinkRequestedView(email: "lord@yosemite.com")
}
}
``` | /content/code_sandbox/Simplenote/MagicLinkRequestedView.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 535 |
```swift
//
// Preferences+IAP.swift
// Simplenote
//
// Created by Jorge Leandro Perez on 10/27/22.
//
import Foundation
// MARK: - Preferences Extensions
//
extension Preferences {
@objc
var isActiveSubscriber: Bool {
subscription_level == StoreConstants.activeSubscriptionLevel
}
@objc
var wasSustainer: Bool {
was_sustainer == true
}
}
``` | /content/code_sandbox/Simplenote/Preferences+IAP.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 95 |
```swift
import UIKit
class NoticeController {
// MARK: Proerties
//
static let shared = NoticeController()
private var current: Notice?
private let noticePresenter: NoticePresenter
private let timerFactory: TimerFactory
private var timer: Timer? {
didSet {
oldValue?.invalidate()
}
}
private var presenting: Bool {
current != nil
}
// MARK: Life Cycle
//
init(presenter: NoticePresenter = NoticePresenter(), timerFactory: TimerFactory = TimerFactory()) {
self.timerFactory = timerFactory
self.noticePresenter = presenter
}
func setupNoticeController() {
noticePresenter.startListeningToKeyboardNotifications()
}
// MARK: Presenting
//
func present(_ notice: Notice) {
if presenting {
dismiss(withDuration: .zero) {
self.present(notice)
}
return
}
current = notice
let noticeView = makeNoticeView(from: notice)
noticePresenter.presentNoticeView(noticeView) {
let delay = self.current?.action == nil ? Times.shortDelay : Times.longDelay
self.timer = self.timerFactory.scheduledTimer(with: delay, completion: {
self.dismiss()
})
}
}
private func makeNoticeView(from notice: Notice) -> NoticeView {
let noticeView: NoticeView = NoticeView.instantiateFromNib()
noticeView.message = notice.message
noticeView.actionTitle = notice.action?.title
noticeView.handler = notice.action?.handler
noticeView.delegate = self
return noticeView
}
// MARK: Dismissing
//
private func dismiss(withDuration duration: TimeInterval = UIKitConstants.animationLongDuration, completion: (() -> Void)? = nil) {
timer = nil
current = nil
noticePresenter.dismissNotification(withDuration: duration) {
completion?()
}
}
}
// MARK: NoticePresenting Delegate
//
extension NoticeController: NoticeInteractionDelegate {
func noticePressBegan() {
timer = nil
}
func noticePressEnded() {
timer = timerFactory.scheduledTimer(with: Times.shortDelay, completion: {
self.dismiss()
})
}
func actionWasTapped() {
dismiss()
}
}
private struct Times {
static let shortDelay = TimeInterval(1.5)
static let longDelay = TimeInterval(2.75)
}
``` | /content/code_sandbox/Simplenote/NoticeController.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 507 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.