Giter Site home page Giter Site logo

bendingspoons / katana-swift Goto Github PK

View Code? Open in Web Editor NEW
2.2K 63.0 90.0 81.35 MB

Swift Apps in a Swoosh! A modern framework for creating iOS apps, inspired by Redux.

Home Page: http://bendingspoons.com

License: MIT License

Swift 97.32% Objective-C 0.46% Shell 0.29% Ruby 1.93%
ios swift ui redux katana

katana-swift's Introduction

Katana

Twitter URL Build Status Docs CocoaPods Licence

Katana is a modern Swift framework for writing iOS applications' business logic that are testable and easy to reason about. Katana is strongly inspired by Redux.

In few words, the app state is entirely described by a single serializable data structure, and the only way to change the state is to dispatch a StateUpdater. A StateUpdater is an intent to transform the state, and contains all the information to do so. Because all the changes are centralized and are happening in a strict order, there are no subtle race conditions to watch out for.

We feel that Katana helped us a lot since we started using it in production. Our applications have been downloaded several millions of times and Katana really helped us scaling them quickly and efficiently. Bending Spoons's engineers leverage Katana capabilities to design, implement and test complex applications very quickly without any compromise to the final result.

We use a lot of open source projects ourselves and we wanted to give something back to the community, hoping you will find this useful and possibly contribute. ❤️

State of the project

We wrote several successful applications using the layer that Katana and Tempura provide. We still think that their approach is really a good one for medium-sized applications but, as our app grows, it becomes increasingly important to have a more modular architecture. For this reason, we have migrated our applications to use The Composable Architecture.

Overview

Your entire app State is defined in a single struct, all the relevant application information should be placed here.

struct CounterState: State {
  var counter: Int = 0
}

The app State can only be modified by a StateUpdater. A StateUpdater represents an event that leads to a change in the State of the app. You define the behaviour of the State Updater by implementing the updateState(:) method that changes the State based on the current app State and the StateUpdater itself. The updateState should be a pure function, which means that it only depends on the inputs (that is, the state and the state updater itself) and it doesn't have side effects, such as network interactions.

struct IncrementCounter: StateUpdater {
  func updateState(_ state: inout CounterState) {
    state.counter += 1
  }
}

The Store contains and manages your entire app State. It is responsible of managing the dispatched items (e.g., the just mentioned State Updater).

// ignore AppDependencies for the time being, it will be explained later on
let store = Store<CounterState, AppDependencies>()
store.dispatch(IncrementCounter())

You can ask the Store to be notified about every change in the app State.

store.addListener() { oldState, newState in
  // the app state has changed
}

Side Effects

Updating the application's state using pure functions is nice and it has a lot of benefits. Applications have to deal with the external world though (e.g., API call, disk files management, …). For all this kind of operations, Katana provides the concept of side effects. Side effects can be used to interact with other parts of your applications and then dispatch new StateUpdaters to update your state. For more complex situations, you can also dispatch other side effects.

Side Effects are implemented on top of Hydra, and allow you to write your logic using promises. In order to leverage this functionality you have to adopt the SideEffect protocol

struct GenerateRandomNumberFromBackend: SideEffect {
  func sideEffect(_ context: SideEffectContext<CounterState, AppDependencies>) throws {
    // invokes the `getRandomNumber` method that returns a promise that is fullfilled
    // when the number is received. At that point we dispatch a State Updater
    // that updates the state
    context.dependencies.APIManager
        .getRandomNumber()
        .then { randomNumber in context.dispatch(SetCounter(newValue: randomNumber)) }
  }
}

struct SetCounter: StateUpdater {
  let newValue: Int
  
  func updateState(_ state: inout CounterState) {
    state.counter = self.newValue
  }
}

Moreover, you can leverage the Hydra.await operator to write logic that mimics the async/await pattern, which allows you to write async code in a sync manner.

struct GenerateRandomNumberFromBackend: SideEffect {
  func sideEffect(_ context: SideEffectContext<CounterState, AppDependencies>) throws {
    // invokes the `getRandomNumber` method that returns a promise that is fulfilled
    // when the number is received.
    let promise = context.dependencies.APIManager.getRandomNumber()
    
    // we use Hydra.await to wait for the promise to be fulfilled
    let randomNumber = try Hydra.await(promise)

    // then the state is updated using the proper state updater
    try Hydra.await(context.dispatch(SetCounter(newValue: randomNumber)))
  }
}

In order to further improve the usability of side effects, there is also a version which can return a value. Note that both the state and dependencies types are erased, to allow for more freedom when using it in libraries, for example.

struct PurchaseProduct: ReturningSideEffect {
  let productID: ProductID

  func sideEffect(_ context: AnySideEffectContext) throws -> Result<PurchaseResult, PurchaseError> {

    // 0. Get the typed version of the context
    guard let context = context as? SideEffectContext<CounterState, AppDependencies> else {
      fatalError("Invalid context type")
    }

    // 1. purchase the product via storekit
    let storekitResult = context.dependencies.monetization.purchase(self.productID)
    if case .failure(let error) = storekitResult {
      return .storekitRejected(error)
    }

    // 2. get the receipt
    let receipt = context.dependencies.monetization.getReceipt()

    // 3. validate the receipt
    let validationResult = try Hydra.await(context.dispatch(Monetization.Validate(receipt)))

    // 4. map error
    return validationResult
      .map { .init(validation: $0) }
      .mapError { .validationRejected($0) }
  }
}

Note that, if this is a prominent use case for the library/app, the step 0 can be encapsulated in a protocol like this:

protocol AppReturningSideEffect: ReturningSideEffect {
  func sideEffect(_ context: SideEffectContext<AppState, DependenciesContainer>) -> Void
}

extension AppReturningSideEffect {
  func sideEffect(_ context: AnySideEffectContext) throws -> Void {
    guard let context = context as? SideEffectContext<AppState, DependenciesContainer> else {
      fatalError("Invalid context type")
    }
    
    self.sideEffect(context)
  }
}

Dependencies

The side effect example leverages an APIManager method. The Side Effect can get the APIManager by using the dependencies parameter of the context. The dependencies container is the Katana way of doing dependency injection. We test our side effects, and because of this we need to get rid of singletons or other bad pratices that prevent us from writing tests. Creating a dependency container is very easy: just create a class that conforms to the SideEffectDependencyContainer protocol, make the store generic to it, and use it in the side effect.

final class AppDependencies: SideEffectDependencyContainer {
  required init(dispatch: @escaping PromisableStoreDispatch, getState: @escaping GetState) {
		// initialize your dependencies here
	}
}

Interceptors

When defining a Store you can provide a list of interceptors that are triggered in the given order whenever an item is dispatched. An interceptor is like a catch-all system that can be used to implement functionalities such as logging or to dynamically change the behaviour of the store. An interceptor is invoked every time a dispatchable item is about to be handled.

DispatchableLogger

Katana comes with a built-in DispatchableLogger interceptor that logs all the dispatchables, except the ones listed in the blacklist parameter.

let dispatchableLogger = DispatchableLogger.interceptor(blackList: [NotToLog.self])
let store = Store<CounterState>(interceptor: [dispatchableLogger])

ObserverInterceptor

Sometimes it is useful to listen for events that occur in the system and react to them. Katana provides the ObserverInterceptor that can be used to achieve this result.

In particular you instruct the interceptor to dispatch items when:

  • the store is initialized
  • the state changes in a particular way
  • a particular dispatchable item is managed by the store
  • a particular notification is sent to the default NotificationCenter
let observerInterceptor = ObserverInterceptor.observe([
  .onStart([
    // list of dispatchable items dispatched when the store is initialized
  ])
])

let store = Store<CounterState>(interceptor: [observerInterceptor])

Note that when intercepting a side effect using an ObserverInterceptor, the return value of the dispatchable is not available to the interceptor itself.

What about the UI?

Katana is meant to give structure to the logic part of your app. When it comes to UI we propose two alternatives:

  • Tempura: an MVVC framework we built on top of Katana and that we happily use to develop the UI of all our apps at Bending Spoons. Tempura is a lightweight, UIKit-friendly library that allows you to keep the UI automatically in sync with the state of your app. This is our suggested choice.

  • Katana-UI: With this library, we aimed to port React to UIKit, it allows you to create your app using a declarative approach. The library was initially bundled together with Katana, we decided to split it as internally we don't use it anymore. In retrospect, we found that the impedance mismatch between the React-like approach and the imperative reality of UIKit was a no go for us.

Tempura Katana UI

Signpost Logger

Katana is automatically integrated with the Signpost API. This integration layer allows you to see in Instruments all the items that have been dispatched, how long they last, and useful pieces of information such as the parallelism degree. Moreover, you can analyse the cpu impact of the items you dispatch to furtherly optimise your application performances.

Bending Spoons Guidelines

In Bending Spoons, we are extensively using Katana. In these years, we've defined some best pratices that have helped us write more readable and easier to debug code. We've decided to open source them so that everyone can have a starting point when using Katana. You can find them here.

Migration from 2.x

We strongly suggest to upgrade to the new Katana. The new Katana, in fact, not only adds new very powerful capabilities to the library, but it has also been designed to be extremely compatible with the old logic. All the actions and middleware you wrote for Katana 2.x, will continue to work in the new Katana as well. The breaking changes are most of the time related to simple typing changes that are easily addressable.

If you prefer to continue with Katana 2.x, however, you can still access Katana 2.x in the dedicated branch.

Middleware

In Katana, the concept of middleware has been replaced with the new concept of interceptor. You can still use your middleware by leveraging the middlewareToInterceptor method.

Swift Version

Certain versions of Katana only support certain versions of Swift. Depending on which version of Swift your project is using, you should use specific versions of Katana. Use this table in order to check which version of Katana you need.

Swift Version Katana Version
Swift 5.0 Katana >= 6.0
Swift 4.2 Katana >= 2.0
Swift 4.1 Katana < 2.0

Where to go from here

Give it a shot

pod try Katana

Tempura

Make awesome applications using Katana together with Tempura

Check out the documentation

Documentation

You can also add Katana to Dash using the proper docset.

Installation

Katana is available through CocoaPods and Swift Package Manager, you can also drop Katana.project into your Xcode project.

Requirements

  • iOS 11.0+ / macOS 10.10+

  • Xcode 9.0+

  • Swift 5.0+

Swift Package Manager

Swift Package Manager is a tool for managing the distribution of Swift code. It’s integrated with the Swift build system to automate the process of downloading, compiling, and linking dependencies.

There are two ways to integrate Katana in your project using Swift Package Manager:

  • Adding it to your Package.swift
  • Adding it directly from Xcode under File -> Swift Packages -> Add Package dependency..

In both cases you only need to provide this URL: [email protected]:BendingSpoons/katana-swift.git

CocoaPods

CocoaPods is a dependency manager for Cocoa projects. You can install it with the following command:

$ sudo gem install cocoapods

To integrate Katana into your Xcode project using CocoaPods you need to create a Podfile.

For iOS platforms, this is the content

use_frameworks!
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '9.0'

target 'MyApp' do
  pod 'Katana'
end

Now, you just need to run:

$ pod install

Get in touch

Special thanks

Contribute

  • If you've found a bug, open an issue;
  • If you have a feature request, open an issue;
  • If you want to contribute, submit a pull request;
  • If you have an idea on how to improve the framework or how to spread the word, please get in touch;
  • If you want to try the framework for your project or to write a demo, please send us the link of the repo.

License

Katana is available under the MIT license.

About

Katana is maintained by Bending Spoons. We create our own tech products, used and loved by millions all around the world. Interested? Check us out!

katana-swift's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

katana-swift's Issues

Create base UI elements

We should create some elements that:

  • we can use to create examples
  • other developers can use to start with Katana

We don't want to add them to the core Katana library, since we really want to allow everyone to use their components without any restriction

Refactor animations

The current animation system is not powerful enough.
We should improve it.

More details coming soon

Fix the "synchronous update" bug

It is currently possible to synchronously invoke the update function in both the render and in the applyProps methods.

This causes undefined behaviours and we should absolutely avoid this case. We can raise an exception for instance and warn the developers to don't do it.

Refactor action system

We have two layers for the actions: normal actions and smart actions. This is very confusing and also the two systems are not compatible.

We should refactor the system in order to have a single approach to actions. It will be also easier to explain going forward

Middleware cannot be shared

StoreMiddleware cannot be shared (e.g., in libraries) because they are generic with respect to the state type. Since Swift doesn't support covariance here, so we can't reuse them.

We should find a fix, since it will be helpful in the future development of Katana

Change The Reference Size (e.g. According to Device Orientation)

After taking a look at the various examples I'm having some problems finding a proper way to change the reference size of a Node.

A typical use case is when the device orientation changes. What we used to do in Plastic was to flip the x and y values of the reference size and change other (usually minor) details in the layout method.

Another use case is if we want to have two or more different layouts when using different devices (e.g. iPhone 4s/7/7plus, iPad/iPad Pro) or when you are in an environment where you can actively change the size of the rendered window (MacOS, multitasking iPad)

I see two ways to potentially fix the issue:

  1. Implement a way to dynamically change the reference size.
  2. Don't change the interface and assume that the reference size will invert it's values when the device orientation is in landscape mode.

My opinion:
Solution 2. would probably be enough to cover most use cases and I think it would be anyways a very good practice to enforce the developers to adopt it by default.

Solution 1. is to be able to define a set of different reference sizes during the Node initialization and have a mechanism that:

  • automatically matches the closest one (first by ratio, then by size);
  • makes it available in both the render and the layout methods in a way that is easily comparable using an if / switch;
  • triggers a render/layout whenever the frame of the reference view changes.
  • keeps the original way of providing just one size which will basically become a shorthand for providing two reference sizes (the provided one and the one with inverted x and y) that, as I said before, would probably cover most of the use cases.

Force Swiftlint Version

We should force a specific version of Swiftlint in the project (and in the examples/demo)

Elements are not correctly reused

I have the feeling that sometimes elements are not reused when they should.
For instance Textfields do not maintain the focus when the state is changed

Define and implement a fully declarative Table and Grid

I'd like to prose a refactor of the table (and the grid) view.
What I propose is a declarative approach where the cell are passed to the table as children, similarly to what we have in a View Node.

Here is how I envision the creation of a Table:

   let table = Table(props: TableProps()) {
      return [
        View(props: ViewProps.build({
          $0.backgroundColor = .red
        })),
        View(props: ViewProps.build({
          $0.backgroundColor = .yellow
        }))
      ]
    }

The table should render the children managing the delegate of its native view. In general different native view should have different strategy when implementing the DrawableContainer protocol. The UIView should add its children as subviews (as it's already implemented), the UITableView should add the children using the native delegate. In the future we might want to add different strategies.

I believe this has two major advantages

  • it allows to use a Table in a much more convenient (and consistent with the rest of the framework) way, without the need of implementing a delegate
  • it allows us to keep a single node three, which allows to remove mangedChildren and to re-introduce alternative Drawable container (that we can use for debugging or profiling proposes)

Here some useful resources:

[Documentation] Issue in UIKit classes extension

For some reasons, the documentation website has an not documented content when we create an extension of a value take from an external framework (e.g., UIKit)

Either we are using Jazzy in a wrong way, or this is a Jazzy bug.
We should investigate

Lifecycle API

We should implement some APIs that allow to customise the behaviour during some lifecycle events. I took inspiration from what React does, and I think those are the hooks that make sense for us

NodeDidMount

static func nodeDidMount(prosp: Props, dispatch: StoreDispatch)

This method is invoked immediately after the node is rendered for the first time. We can leverage this to trigger APIs calls when the UI appears (e.g., load proper data). The name could also be nodeDidRender but I decided for didMount to be symmetric with nodeWillUnmount (more appropriated names are welcome)

DescriptionWillReceiveProps

static func descriptionWillReceiveProps(currentProps: Props, nextProps, dispatch: StoreDispatch, update: StateUpdateFn)

This method is invoked just before the render is performed because of new properties. We can use this method to update the state according to new props or to properly dispatch actions.

Note: using the update function should work as expected. The next render should have both state and props properly update. We shouldn't trigger 2 description updates

NodeWillUnmount

static func nodeWillUnmount(prosp: Props, dispatch: StoreDispatch)

This method is invoked just before a Node is removed from the UI hierarchy for good. We can use this to make cleanup operations in the state. As in NodeDidMount, better names are welcome

The fill method of PlasticView is ambiguously named

It has happened to me a few times that I wanted to use the fill method and got surprised by the behaviour. I called it this way view.fill(top: anchor1, left: anchor2, bottom: anchor3, right: anchor4) and expected my view to stretch to the anchors, instead I got a square view.

This is because fill stretches the view preserving the aspect ratio (1, by default). I think the method should be renamed to something like fillPreservingAspectRatio to avoid confusion, or at least the scale argument shouldn't be optional.

Moreover, I think it would be useful to have a fill method that does not preserve the aspect ratio.

SyncAction/AsyncAction should be improved

In the last few days I've reviewed a lot of code and I think that we have an intrinsic problem with these two protocols.

Forcing people to put everything in the payload leads to very weird things and in general to hard to understand actions. We should release this constraint.

A little bit of background: forcing to use payload has been added to write an automated way to serialize/deserialize actions. I think we have not better ways to do it and therefore it shouldn't be a problem anymore.

My only concern is about asyncActions. We should find a way to keep the functionalities without forcing people to use names such as payload or completedPayload.
Note that using asyncActions is very verbose right now as we cannot automate very little using the protocol extensions. Maybe it is time to think to a better way to manage the problem of having an action that can be "completed" and that can "fail" without having 3 actions. In this context, if possible, we should also add a way to manage progression (e.g., download of a file)

Add an example about wrapping Apple view controllers

In Bending Spoons we like to have our own version of most the UIKit's elements and Katana is very in line with this philosophy.

That said, this is not something we can ask to people that use Katana. In particular Apple provides a widely used view controllers that are used for navigation within iOS applications (e.g., TabBar, NavigationController, ...).

It is totally possible to wrap these view controllers in Katana descriptions and expose an interface to use them. We should provide an example for the community that acts as a starting point for this kind of situations. I suggest to use the navigation example since it is most likely the most common one.

Note that we have a fully declarative, Katana based solution for navigation, but we is not public (yet) because it is at the moment strongly tied to internal conventions and technologies. Moreover it doesn't really solve the problem of using UIKit view controllers, so it isn't a real solution to this issue.

0.2.0 Release

@alaincaltieri we should release Katana 0.2.0 as well as KatanaElements (same version)

### CHANGELOG
#### Breaking changes
* `static func updateState(action:currentState:)` is now `func updateState(currentState:)`. See [this PR](https://github.com/BendingSpoons/katana-swift/pull/68) for more information. Thanks @Danappelxx

#### Non breaking changes
* Fix Demo (affects `pod try`)
* Minor internal fixes

Refactor Node init

the current Node init

public init(description: Description, parent: AnyNode? = nil, root: Root? = nil) {

is very weird. I'd put it private and add two different init: one with parent and one with root.

What do you think?

Write a great README

As discussed we want to touch the following points (more or less in deep) in the README

  • Background (react/redux)
  • History, why we have created Katana
  • How to use it
  • Very simple getting started (ideally max 10 lines for an hello world)
  • “We use it in production”
  • Roadmap
  • Why do we release Katana as OSS?

Let's take a look at other well done README for inspiration.

This is also an interesting resource

Write documentation

Let's use Jazzy for the documentation.
We also want to be compatible with CocoaDocs so we should investigate whether we need do to something special in order to support it

Reducers?

I just have a simple question as I've been using Redux directly for the last few months:

Where are the Reducers?

It seems like you are putting all your state mutation code inside your actions. Is this a pattern that you adopted on purpose and if so then why?

EdgeInsets for Vertical and Horizonal Layout Methods Are Misleading

As horizontal and vertical components of EdgeInsets are ignored when passed respectively to vertical and horizontal filling methods, we probably should consider adding VerticalEdgeInsets and HorizontalEdgeInsets types and use them as required types for these methods

Store unsubscribe in `Root`

var unsubscribe: StoreUnsubscribe? in Root is public. I think this is an internal implementation detail and should be private

Write a simple example

Write an example that can be used to have an overview of Katana without too many complications (e.g., authentication)

Add support for external libraries with actions

Side effects currently require a generic container as the last parameter. The problem with this approach is that it doesn't allow to have libraries with actions that can be used in every application.

We should find a better approach to manage providers

[Readme] Existing project integration

It is very easy to integrate Katana in existing projects (e.g., use it just for a piece of an application or gradually adopt the Katana approach in old apps).
That said we don't have anything in the readme that mention that. We should absolutely add this to the README to help people jump on board.

In the end it just a matter of render a node description somewhere in the application (e.g., a view controller) rather than doing it in the AppDelegate. It is as simple as that

Root init method and `node` var

The Root class has the following code

  public var node: AnyNode? {
    willSet(node) {
      if self.node != nil {
        fatalError("node cannot be changed")
      }
    }
  }

wouldn't be better to update the init to take the node, and make it readonly (let)?

Probably unnecessary throw

The Node function func update(with description: AnyNodeDescription) throws may throw an exception but actually there is no code that does it.
It think it is a refuse of a previous Node implementation

Can we remove it?

Node root and treeRoot confusion

Node exposes two properties

  • root which has a value only if the parent of the node is a root, and it is the root itself
  • treeRoot which is the root of the tree, independently on which node the property is get

In addition to that, there is also parent which is the parent of the Node instance, but only if the parent is not Root, because in this case root has a value and parent is nil

In general I think this is super confusing and we should do something about it.
My proposal is to make root private, since we never use it and then always use treeRoot when needed.

We should also define what happens when the parent of a node is root. Right now we can't just return Root in parent because Root is not a subclass of Node

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.