Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
13 changes: 13 additions & 0 deletions Example/AsyncReactorExample.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
80D30FC62A1CDBC200C653B0 /* RepositoryDescriptionSheet.swift in Sources */ = {isa = PBXBuildFile; fileRef = 80D30FC52A1CDBC200C653B0 /* RepositoryDescriptionSheet.swift */; };
80E8B9D12A1BAE2800E4B3CC /* RepositorySearchView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 80E8B9D02A1BAE2800E4B3CC /* RepositorySearchView.swift */; };
80E8B9D32A1BAEC200E4B3CC /* RepositoryDetailView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 80E8B9D22A1BAEC200E4B3CC /* RepositoryDetailView.swift */; };
B4335C542A5FEAAD001B16EA /* GitHubAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = B4335C532A5FEAAD001B16EA /* GitHubAPI.swift */; };
B43CC1B52A6154E30051AD5B /* Macro in Frameworks */ = {isa = PBXBuildFile; productRef = B43CC1B42A6154E30051AD5B /* Macro */; };
B4ECB0B02A1250AE00B0CAAE /* AsyncReactorExampleApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = B4ECB0AF2A1250AE00B0CAAE /* AsyncReactorExampleApp.swift */; };
B4ECB0B22A1250AE00B0CAAE /* ContentView.swift in Sources */ = {isa = PBXBuildFile; fileRef = B4ECB0B12A1250AE00B0CAAE /* ContentView.swift */; };
B4ECB0B42A1250AF00B0CAAE /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = B4ECB0B32A1250AF00B0CAAE /* Assets.xcassets */; };
Expand All @@ -31,6 +33,8 @@
80D30FC52A1CDBC200C653B0 /* RepositoryDescriptionSheet.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RepositoryDescriptionSheet.swift; sourceTree = "<group>"; };
80E8B9D02A1BAE2800E4B3CC /* RepositorySearchView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RepositorySearchView.swift; sourceTree = "<group>"; };
80E8B9D22A1BAEC200E4B3CC /* RepositoryDetailView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RepositoryDetailView.swift; sourceTree = "<group>"; };
B4335C532A5FEAAD001B16EA /* GitHubAPI.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GitHubAPI.swift; sourceTree = "<group>"; };
B4335C552A5FF25F001B16EA /* Macro */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = Macro; path = ../Macro; sourceTree = "<group>"; };
B4ECB0AC2A1250AE00B0CAAE /* AsyncReactorExample.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = AsyncReactorExample.app; sourceTree = BUILT_PRODUCTS_DIR; };
B4ECB0AF2A1250AE00B0CAAE /* AsyncReactorExampleApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AsyncReactorExampleApp.swift; sourceTree = "<group>"; };
B4ECB0B12A1250AE00B0CAAE /* ContentView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ContentView.swift; sourceTree = "<group>"; };
Expand All @@ -46,6 +50,7 @@
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
B43CC1B52A6154E30051AD5B /* Macro in Frameworks */,
B4ECB0C82A12520700B0CAAE /* Logging in Frameworks */,
B4ECB0C12A1250E000B0CAAE /* AsyncReactor in Frameworks */,
);
Expand Down Expand Up @@ -86,6 +91,7 @@
80E8B9D02A1BAE2800E4B3CC /* RepositorySearchView.swift */,
80D30FC12A1BBF9A00C653B0 /* RepositoryList.swift */,
80D30FC32A1BC07B00C653B0 /* RepositoryItem.swift */,
B4335C532A5FEAAD001B16EA /* GitHubAPI.swift */,
);
path = Search;
sourceTree = "<group>";
Expand All @@ -103,6 +109,7 @@
B4ECB0A32A1250AE00B0CAAE = {
isa = PBXGroup;
children = (
B4335C552A5FF25F001B16EA /* Macro */,
B4ECB0BE2A1250D700B0CAAE /* AsyncReactor */,
B4ECB0AE2A1250AE00B0CAAE /* AsyncReactorExample */,
B4ECB0AD2A1250AE00B0CAAE /* Products */,
Expand Down Expand Up @@ -166,6 +173,7 @@
packageProductDependencies = (
B4ECB0C02A1250E000B0CAAE /* AsyncReactor */,
B4ECB0C72A12520700B0CAAE /* Logging */,
B43CC1B42A6154E30051AD5B /* Macro */,
);
productName = AsyncReactorExample;
productReference = B4ECB0AC2A1250AE00B0CAAE /* AsyncReactorExample.app */;
Expand Down Expand Up @@ -233,6 +241,7 @@
B4ECB0C42A1251B500B0CAAE /* RepositorySearchReactor.swift in Sources */,
80D30FBE2A1BBD8000C653B0 /* RepositoryDetailReactor.swift in Sources */,
80E8B9D12A1BAE2800E4B3CC /* RepositorySearchView.swift in Sources */,
B4335C542A5FEAAD001B16EA /* GitHubAPI.swift in Sources */,
80D30FC42A1BC07B00C653B0 /* RepositoryItem.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
Expand Down Expand Up @@ -456,6 +465,10 @@
/* End XCRemoteSwiftPackageReference section */

/* Begin XCSwiftPackageProductDependency section */
B43CC1B42A6154E30051AD5B /* Macro */ = {
isa = XCSwiftPackageProductDependency;
productName = Macro;
};
B4ECB0C02A1250E000B0CAAE /* AsyncReactor */ = {
isa = XCSwiftPackageProductDependency;
productName = AsyncReactor;
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion Example/AsyncReactorExample/ContentView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,18 @@ import AsyncReactor

struct ContentView: View {
var body: some View {
ReactorView(RepositorySearchReactor()) {
RepositorySearchReactorView {
RepositorySearchView()
}
.environment(\.gitHubApi, GitHubAPI())
}
}

struct ContentView_Previews: PreviewProvider {
static var previews: some View {
NavigationStack {
ContentView()
.environment(\.gitHubApi, GitHubAPI())
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
//
// GitHubAPI.swift
// AsyncReactorExample
//
// Created by Dominik Arnhof on 13.07.23.
//

import SwiftUI

struct GitHubAPI {
func search(query: String) async throws -> [Repository] {
let (data, _) = try await URLSession.shared.data(from: URL(string:"https://api.github.com/search/repositories?q=\(query)")!)
let decodedResponse = try JSONDecoder().decode(RepositoriesResponse.self, from: data)
return decodedResponse.repositories
}
}

private struct GitHubAPIKey: EnvironmentKey {
static var defaultValue: GitHubAPI? = nil
}

extension EnvironmentValues {
var gitHubApi: GitHubAPI? {
get { self[GitHubAPIKey.self] }
set { self[GitHubAPIKey.self] = newValue }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import Foundation
import AsyncReactor
import UIKit
import Logging
import Macro
import SwiftUI

private let logger = Logger(label: "RepositorySearchReactor")

Expand All @@ -28,7 +30,8 @@ enum SortOptions: String, CaseIterable, Identifiable {
}
}

class RepositorySearchReactor: AsyncReactor {
@Reactor
class RepositorySearchReactor {
enum Action {
case onHidePrivateToggle
case enterQuery(String)
Expand All @@ -44,8 +47,11 @@ class RepositorySearchReactor: AsyncReactor {
var sortBy: SortOptions = .watchers
}

@Published
private(set) var state: State
@Dependency(\.gitHubApi)
var gitHubApi

@Dependency(\.managedObjectContext)
var hallo

@MainActor
init(state: State = State()) {
Expand All @@ -63,31 +69,31 @@ class RepositorySearchReactor: AsyncReactor {
}
}

@MainActor // NOTE: when adding AsyncReactor conformance via macro, @MainActor is not automatically added apparently...
func action(_ action: Action) async {
switch action {
case .onHidePrivateToggle:
state.hidePrivate.toggle()

case .enterQuery(let query):
print("enter query: \(query)")
state.query = query

try? await Task.sleep(for: .seconds(1))

guard !Task.isCancelled else { return }

print("load")
await self.action(.load)
case .load:
state.isLoading = true

do {
let currentQuery = state.query.isEmpty ? "iOS" : state.query
let (data, _) = try await URLSession.shared.data(from: URL(string:"https://api.github.com/search/repositories?q=\(currentQuery)")!)
let decodedResponse = try JSONDecoder().decode(RepositoriesResponse.self, from: data)

state.repositories = decodedResponse.repositories
state.repositories = try await gitHubApi!.search(query: currentQuery)
state.isLoading = false

logger.debug("search repositories success: \(String(describing: decodedResponse.repositories.count))")
logger.debug("search repositories success: \(String(describing: state.repositories.count))")
}
catch {
logger.error("error while searching repositories: \(error)")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ struct RepositorySearchView: View {
var body: some View {
NavigationStack {
List {
TextField("", text: $query)

Toggle("Hide Private Repos", isOn: $hidePrivate)

if reactor.isLoading {
Expand Down Expand Up @@ -57,7 +59,7 @@ struct RepositorySearchView: View {
.refreshable {
reactor.send(.load)
}
.searchable(text: $query)
// .searchable(text: $query)
.toolbar {
ToolbarItem {
Menu("Sort By") {
Expand Down
8 changes: 8 additions & 0 deletions Macro/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
.DS_Store
/.build
/Packages
xcuserdata/
DerivedData/
.swiftpm/configuration/registries.json
.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata
.netrc
53 changes: 53 additions & 0 deletions Macro/Package.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
// swift-tools-version: 5.9
// The swift-tools-version declares the minimum version of Swift required to build this package.

import PackageDescription
import CompilerPluginSupport

let package = Package(
name: "Macro",
platforms: [.macOS(.v12), .iOS(.v15), .tvOS(.v13), .watchOS(.v6), .macCatalyst(.v13)],
products: [
// Products define the executables and libraries a package produces, making them visible to other packages.
.library(
name: "Macro",
targets: ["Macro"]
),
.executable(
name: "MacroClient",
targets: ["MacroClient"]
),
],
dependencies: [
// Depend on the latest Swift 5.9 prerelease of SwiftSyntax
.package(url: "https://github.com/apple/swift-syntax.git", from: "509.0.0-swift-5.9-DEVELOPMENT-SNAPSHOT-2023-04-25-b"),
.package(name: "AsyncReactor", path: "../")
],
targets: [
// Targets are the basic building blocks of a package, defining a module or a test suite.
// Targets can depend on other targets in this package and products from dependencies.
// Macro implementation that performs the source transformation of a macro.
.macro(
name: "MacroMacros",
dependencies: [
.product(name: "SwiftSyntaxMacros", package: "swift-syntax"),
.product(name: "SwiftCompilerPlugin", package: "swift-syntax")
]
),

// Library that exposes a macro as part of its API, which is used in client programs.
.target(name: "Macro", dependencies: ["MacroMacros"]),

// A client of the library, which is able to use the macro in its own code.
.executableTarget(name: "MacroClient", dependencies: ["Macro", "AsyncReactor"]),

// A test target used to develop the macro implementation.
.testTarget(
name: "MacroTests",
dependencies: [
"MacroMacros",
.product(name: "SwiftSyntaxMacrosTestSupport", package: "swift-syntax"),
]
),
]
)
20 changes: 20 additions & 0 deletions Macro/Sources/Macro/Macro.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// The Swift Programming Language
// https://docs.swift.org/swift-book

import AsyncReactor

/// A macro that produces both a value and a string containing the
/// source code that generated the value. For example,
///
/// #stringify(x + y)
///
/// produces a tuple `(x + y, "x + y")`.
@freestanding(expression)
public macro stringify<T>(_ value: T) -> (T, String) = #externalMacro(module: "MacroMacros", type: "StringifyMacro")

@attached(extension, conformances: AsyncReactor)
@attached(member, names: named(state))
@attached(peer, names: suffixed(View))
public macro Reactor() = #externalMacro(module: "MacroMacros", type: "ReactorMacro")

//@attached(member, names: named(_$backingData), named(backingData), named(schemaMetadata), named(`init`), named(_$observationRegistrar)) @attached(memberAttribute) @attached(conformance) public macro Model() = #externalMacro(module: "SwiftDataMacros", type: "PersistentModelMacro")
40 changes: 40 additions & 0 deletions Macro/Sources/MacroClient/main.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import Macro
import SwiftData
import AsyncReactor
import SwiftUI

let a = 17
let b = 25

let (result, code) = #stringify(a + b)

print("The value \(result) was produced by the code \"\(code)\"")

@Reactor
class TestReactor {
enum Action {
case search(String)
}

struct State {
var query = ""
}

@Dependency(\.managedObjectContext)
var context

@Dependency(\.colorScheme)
var colorScheme

@MainActor
init(state: State = State()) {
self.state = state
}

func action(_ action: Action) async {
switch action {
case .search(let string):
print(string)
}
}
}
Loading