Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,9 @@ let package = Package(
from: "1.1.1"
),
.package(
url: "https://github.com/0xOpenBytes/t",
from: "0.2.0"
)
url: "https://github.com/0xLeif/swift-custom-dump",
from: "0.4.1"
)
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
Expand All @@ -35,7 +35,7 @@ let package = Package(
name: "CacheStore",
dependencies: [
"c",
"t"
.product(name: "CustomDump", package: "swift-custom-dump")
]
),
.testTarget(
Expand Down
233 changes: 160 additions & 73 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,118 +1,205 @@
# CacheStore

*SwiftUI Observable Cache*
*SwiftUI State Management*

## What is `CacheStore`?

`CacheStore` is a SwiftUI framework to help with state. Define keyed values that you can share locally or globally in your projects. `CacheStore` uses [`c`](https://github.com/0xOpenBytes/c), which a simple composition framework. [`c`](https://github.com/0xOpenBytes/c) has the ability to create transformations that are either unidirectional or bidirectional. There is also a cache that values can be set and resolved, which is used in `CacheStore`.
`CacheStore` is a SwiftUI tate management framework that uses a dictionary as the state. Scoping creates a single source of truth for the parent state. `CacheStore` uses [`c`](https://github.com/0xOpenBytes/c), which a simple composition framework. [`c`](https://github.com/0xOpenBytes/c) has the ability to create transformations that are either unidirectional or bidirectional.

### CacheStore Basic Idea

A `[AnyHashable: Any]` can be used as the single source of truth for an app. Scoping can be done by limiting the known keys. Modification to the scoped value or parent value should be reflected throughout the app.

## Objects
- `CacheStore`: An object that needs defined Keys to get and set values.
- `Store`: An object that needs defined Keys, Actions, and Dependencies. (Preferred)
- `TestStore`: A testable wrapper around `Store` to make it easy to write XCTestCases

## Store
### Store

A `Store` is an object that you send actions to and read state from. Stores use a private `CacheStore` to manage state behind the scenes. All state changes must be defined in a `StoreActionHandler` where the state gets modified depending on an action.
A `Store` is an object that you send actions to and read state from. Stores use a `CacheStore` to manage state behind the scenes. All state changes must be defined in a `StoreActionHandler` where the state gets modified depending on an action.

## Basic Store Example
### TestStore

Here is a basic `Store` example where this is a Boolean variable called `isOn`. The only way you can modify that variable is be using defined actions for the given store. In this example there is only one action, toggle.
When creating tests you should use `TestStore` to send and receive actions while making expectations. If any expectation is false it will be reported in a `XCTestCase`. If there are any effects left at the end of the test, there will be a failure as all effects must be completed and all resulting actions handled. `TestStore` uses a FIFO (first in first out) queue to manage the effects.

```swift
enum StoreKey {
case isOn
}
## Basic Usage

enum Action {
case toggle
}

let actionHandler = StoreActionHandler<StoreKey, Action, Void> { (store: inout CacheStore<StoreKey>, action: Action, _: Void) in
switch action {
case .toggle:
store.update(.isOn, as: Bool.self, updater: { $0?.toggle() })
}
}
<details>
<summary>Store Example</summary>

let store = Store<StoreKey, Action, Void>(
initialValues: [.isOn: false],
actionHandler: actionHandler,
dependency: ()
)
```swift
import CacheStore
import SwiftUI

try t.assert(store.get(.isOn), isEqualTo: false)
struct Post: Codable, Hashable {
var id: Int
var userId: Int
var title: String
var body: String
}

store.handle(action: .toggle)
enum StoreKey {
case url
case posts
case isLoading
}

try t.assert(store.get(.isOn), isEqualTo: true)
```
enum Action {
case fetchPosts
case postsResponse(Result<[Post], Error>)
}

## Basic CacheStore Example
extension String: Error { }

Here is a simple application that has two files, an `App` file and `ContentView` file. The `App` contains the `StateObject` `CacheStore`. It then adds the `CacheStore` to the global cache using [`c`](https://github.com/0xOpenBytes/c). `ContentView` can then resolve the cache as an `ObservableObject` which can read or write to the cache. The cache can be injected into the `ContentView` directly, see `ContentView_Previews`, or indirectly, see `ContentView`.
struct Dependency {
var fetchPosts: (URL) async -> Result<[Post], Error>
}

```swift
import c
import CacheStore
import SwiftUI
extension Dependency {
static var mock: Dependency {
Dependency(
fetchPosts: { _ in
sleep(1)
return .success([Post(id: 1, userId: 1, title: "Mock", body: "Post")])
}
)
}

static var live: Dependency {
Dependency { url in
do {
let (data, _) = try await URLSession.shared.data(from: url)
return .success(try JSONDecoder().decode([Post].self, from: data))
} catch {
return .failure(error)
}
}
}
}

enum CacheKey: Hashable {
case someValue
let actionHandler = StoreActionHandler<StoreKey, Action, Dependency> { cacheStore, action, dependency in
switch action {
case .fetchPosts:
struct FetchPostsID: Hashable { }

guard let url = cacheStore.get(.url, as: URL.self) else {
return ActionEffect(.postsResponse(.failure("Key `.url` was not a URL")))
}

cacheStore.set(value: true, forKey: .isLoading)

return ActionEffect(id: FetchPostsID()) {
.postsResponse(await dependency.fetchPosts(url))
}

case let .postsResponse(.success(posts)):
cacheStore.set(value: false, forKey: .isLoading)
cacheStore.set(value: posts, forKey: .posts)

case let .postsResponse(.failure(error)):
cacheStore.set(value: false, forKey: .isLoading)
}

return .none
}

@main
struct DemoApp: App {
@StateObject var cacheStore = CacheStore<CacheKey>(
initialValues: [.someValue: "🥳"]
struct ContentView: View {
@ObservedObject var store: Store<StoreKey, Action, Dependency> = .init(
initialValues: [
.url: URL(string: "https://jsonplaceholder.typicode.com/posts") as Any
],
actionHandler: actionHandler,
dependency: .live
)
.debug

var body: some Scene {
c.set(value: cacheStore, forKey: "CacheStore")

return WindowGroup {
VStack {
Text("@StateObject value: \(cacheStore.resolve(.someValue) as String)")
ContentView()
private var isLoading: Bool {
store.get(.isLoading, as: Bool.self) ?? true
}

var body: some View {
if
!isLoading,
let posts = store.get(.posts, as: [Post].self)
{
List(posts, id: \.self) { post in
Text(post.title)
}
} else {
ProgressView()
.onAppear {
store.handle(action: .fetchPosts)
}
}
}
}

```

### ContentView
</details>

<details>
<summary>Testing</summary>

```swift
import c
import CacheStore
import SwiftUI
import XCTest
@testable import CacheStoreDemo

struct ContentView: View {
@ObservedObject var cacheStore: CacheStore<CacheKey> = c.resolve("CacheStore")

var stringValue: String {
cacheStore.resolve(.someValue)
class CacheStoreDemoTests: XCTestCase {
override func setUp() {
TestStoreFailure.handler = XCTFail
}

var body: some View {
VStack {
Text("Current Value: \(stringValue)")
Button("Update Value") {
cacheStore.set(value: ":D", forKey: .someValue)
}
func testExample_success() throws {
let store = TestStore(
initialValues: [
.url: URL(string: "https://jsonplaceholder.typicode.com/posts") as Any
],
actionHandler: actionHandler,
dependency: .mock
)

store.send(.fetchPosts) { cacheStore in
cacheStore.set(value: true, forKey: .isLoading)
}
store.send(.fetchPosts) { cacheStore in
cacheStore.set(value: true, forKey: .isLoading)
}

let expectedPosts: [Post] = [Post(id: 1, userId: 1, title: "Mock", body: "Post")]

store.receive(.postsResponse(.success(expectedPosts))) { cacheStore in
cacheStore.set(value: false, forKey: .isLoading)
cacheStore.set(value: expectedPosts, forKey: .posts)
}
.padding()
}
}

struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView(
cacheStore: CacheStore(
initialValues: [.someValue: "Preview Cache Value"]
)
func testExample_failure() throws {
let store = TestStore(
initialValues: [
:
],
actionHandler: actionHandler,
dependency: .mock
)

store.send(.fetchPosts, expecting: { _ in })

store.receive(.postsResponse(.failure("Key `.url` was not a URL"))) { cacheStore in
cacheStore.set(value: false, forKey: .isLoading)
}
}
}

```

</details>

***

## Acknowledgement of Dependencies
- [pointfreeco/swift-custom-dump](https://github.com/pointfreeco/swift-custom-dump)


## Inspiration
- [pointfreeco/swift-composable-architecture](https://github.com/pointfreeco/swift-composable-architecture)
48 changes: 44 additions & 4 deletions Sources/CacheStore/Actions/ActionHandling.swift
Original file line number Diff line number Diff line change
@@ -1,24 +1,64 @@
import Foundation

/// ActionHandlers can handle any value of `Action`. Normally `Action` is an enum.
public protocol ActionHandling {
/// `Action` Type that is passed into the handle function
associatedtype Action

/// Handle the given `Action`
func handle(action: Action)
}

/// Async effect produced from an `Action` that can optionally produce another `Action`
public struct ActionEffect<Action> {
/// ID used to identify and cancel the effect
public let id: AnyHashable
/// Async closure that optionally produces an `Action`
public let effect: () async -> Action?

/// No effect
public static var none: Self {
ActionEffect { nil }
}

/// init for `ActionEffect<Action>` taking an async effect
public init(
id: AnyHashable = UUID(),
effect: @escaping () async -> Action?
) {
self.id = id
self.effect = effect
}

/// init for `ActionEffect<Action>` taking an immediate action
public init(_ action: Action) {
self.id = UUID()
self.effect = { action }
}
}

/// Handles an `Action` that modifies a `CacheStore` using a `Dependency`
public struct StoreActionHandler<Key: Hashable, Action, Dependency> {
private let handler: (inout CacheStore<Key>, Action, Dependency) -> Void
private let handler: (inout CacheStore<Key>, Action, Dependency) -> ActionEffect<Action>?

/// init for `StoreActionHandler<Key: Hashable, Action, Dependency>`
public init(
_ handler: @escaping (inout CacheStore<Key>, Action, Dependency) -> Void
_ handler: @escaping (inout CacheStore<Key>, Action, Dependency) -> ActionEffect<Action>?
) {
self.handler = handler
}

/// `StoreActionHandler` that doesn't handle any `Action`
public static var none: StoreActionHandler<Key, Action, Dependency> {
StoreActionHandler { _, _, _ in }
StoreActionHandler { _, _, _ in nil }
}

public func handle(store: inout CacheStore<Key>, action: Action, dependency: Dependency) {
/// Mutate `CacheStore<Key>` for `Action` with `Dependency`
public func handle(
store: inout CacheStore<Key>,
action: Action,
dependency: Dependency
) -> ActionEffect<Action>? {
handler(&store, action, dependency)
}
}
Loading