Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add @EnvironmentObject #170

Merged
merged 10 commits into from
Jul 17, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
9 changes: 9 additions & 0 deletions Package.resolved
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,15 @@
"version": null
}
},
{
"package": "OpenCombine",
"repositoryURL": "https://github.com/MaxDesiatov/OpenCombine.git",
"state": {
"branch": "wasi",
"revision": "4fed049b0ab7095d4d26247ef958d3f6e361c569",
"version": null
}
},
{
"package": "Runtime",
"repositoryURL": "https://github.com/MaxDesiatov/Runtime.git",
Expand Down
3 changes: 2 additions & 1 deletion Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ let package = Package(
// .package(url: /* package url */, from: "1.0.0"),
.package(url: "https://github.com/kateinoigakukun/JavaScriptKit.git", .revision("47f2bb1")),
.package(url: "https://github.com/MaxDesiatov/Runtime.git", .branch("wasi-build")),
.package(url: "https://github.com/MaxDesiatov/OpenCombine.git", .branch("wasi")),
],
targets: [
// Targets are the basic building blocks of a package. A target can define
Expand All @@ -34,7 +35,7 @@ let package = Package(
// in packages which this package depends on.
.target(
name: "TokamakCore",
dependencies: ["Runtime"]
dependencies: ["Runtime", "OpenCombine"]
),
.target(
name: "TokamakDemo",
Expand Down
2 changes: 1 addition & 1 deletion Sources/TokamakCore/Environment/Environment.swift
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ protocol EnvironmentReader {
case value(Value)
}

var content: Environment<Value>.Content
var content: Content
let keyPath: KeyPath<EnvironmentValues, Value>
public init(_ keyPath: KeyPath<EnvironmentValues, Value>) {
content = .keyPath(keyPath)
Expand Down
77 changes: 77 additions & 0 deletions Sources/TokamakCore/Environment/EnvironmentObject.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
// Copyright 2020 Tokamak contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Created by Carson Katri on 7/7/20.
//

import OpenCombine

protocol EnvironmentWriter {
func subscribe(_ closure: @escaping () -> ())
}

@propertyWrapper public struct EnvironmentObject<ObjectType>: EnvironmentReader, EnvironmentWriter where ObjectType: ObservableObject {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • 🚫 Line should be 100 characters or less: currently 135 characters (line_length)

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • 🚫 Line should be 100 characters or less: currently 135 characters (line_length)

@dynamicMemberLookup public struct Wrapper {
internal let root: ObjectType
public subscript<Subject>(dynamicMember keyPath: ReferenceWritableKeyPath<ObjectType, Subject>) -> Binding<Subject> {
Binding {
root[keyPath: keyPath]
} set: {
root[keyPath: keyPath] = $0
}
}
}

var _store: ObjectType?
var _seed: Int = 0

mutating func setContent(from values: EnvironmentValues) {
_store = values[ObjectIdentifier(ObjectType.self)]
}

func subscribe(_ closure: @escaping () -> ()) {
_ = _store?.objectWillChange.sink { _ in
print("EnvironmentObject changed!")
closure()
}
}

public var wrappedValue: ObjectType {
guard let store = _store else { error() }
return store
}

public var projectedValue: Wrapper {
guard let store = _store else { error() }
return Wrapper(root: store)
}

func error() -> Never {
fatalError("No ObservableObject found for type \(ObjectType.self)")
}

public init() {}
}

extension ObservableObject {
static var environmentStore: WritableKeyPath<EnvironmentValues, Self?> {
\.[ObjectIdentifier(self)]
}
}

extension View {
public func environmentObject<B>(_ bindable: B) -> some View where B: ObservableObject {
environment(B.environmentStore, bindable)
}
}
11 changes: 11 additions & 0 deletions Sources/TokamakCore/Environment/EnvironmentValues.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
// See the License for the specific language governing permissions and
// limitations under the License.

import OpenCombine

public struct EnvironmentValues: CustomStringConvertible {
public var description: String {
String(describing: values)
Expand All @@ -32,4 +34,13 @@ public struct EnvironmentValues: CustomStringConvertible {
values[ObjectIdentifier(key)] = newValue
}
}

subscript<B>(bindable: ObjectIdentifier) -> B? where B: ObservableObject {
get {
values[bindable] as? B
}
set {
values[bindable] = newValue
}
}
}
11 changes: 11 additions & 0 deletions Sources/TokamakCore/MountedViews/MountedView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,17 @@ extension View {
try! prop.set(value: wrapper, on: &extractedView)
// swiftlint:enable force_cast
}

// Setup onEnvironmentChanged for all @EnvironmentObject
for prop in viewInfo.properties.filter({ $0.type is EnvironmentWriter.Type }) {
// swiftlint:disable force_cast
let wrapper = try! prop.get(from: any.view) as! EnvironmentWriter
wrapper.subscribe {
print("Environment changed (received on reconciler)")
}
// swiftlint:enable force_cast
}

// Set the extractedView back on the AnyView after modification
let anyViewInfo = try! typeInfo(of: AnyView.self)
try! anyViewInfo.property(named: "view").set(value: extractedView, on: &injectableView)
Expand Down
2 changes: 2 additions & 0 deletions Sources/TokamakCore/StackReconciler.swift
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,8 @@ public final class StackReconciler<R: Renderer> {
// swiftlint:disable force_try
let info = try! typeInfo(of: compositeView.view.type)
let stateProperties = info.properties.filter { $0.type is ValueStorage.Type }
let environmentObjects = info.properties.filter { $0.type is EnvironmentReader.Type }
print(environmentObjects)

for (id, stateProperty) in stateProperties.enumerated() {
// `ValueStorage` properties were already filtered out, so safe to assume the value's type
Expand Down
1 change: 1 addition & 0 deletions Sources/TokamakDOM/Environment/Environment.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,4 @@
import TokamakCore

public typealias Environment = TokamakCore.Environment
public typealias EnvironmentObject = TokamakCore.EnvironmentObject
24 changes: 20 additions & 4 deletions Sources/TokamakDemo/EnvironmentDemo.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,17 +18,33 @@
#if canImport(SwiftUI)
import SwiftUI
#else
import OpenCombine
import TokamakDOM
#endif

class TestEnvironment: ObservableObject {
var envTest = "Hello, world!" {
willSet {
print(newValue)
objectWillChange.send()
}
}

let objectWillChange = ObservableObjectPublisher()

init() {}
}

struct EnvironmentDemo: View {
@Environment(\.font) var font: Font?
@EnvironmentObject var testEnv: TestEnvironment

var body: some View {
if let font = font {
return Text("\(String(describing: font))")
} else {
return Text("`font` environment not set.")
VStack {
Text(font == nil ? "`font` environment not set." : "\(String(describing: font!))")
Button(testEnv.envTest) {
testEnv.envTest = "EnvironmentObject modified."
}
}
}
}
1 change: 1 addition & 0 deletions Sources/TokamakDemo/TokamakDemo.swift
Original file line number Diff line number Diff line change
Expand Up @@ -61,5 +61,6 @@ struct TokamakDemoView: View {
}
}
}
.environmentObject(TestEnvironment())
}
}
1 change: 1 addition & 0 deletions Sources/TokamakDemo/main.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
// limitations under the License.

import JavaScriptKit
import OpenCombine
carson-katri marked this conversation as resolved.
Show resolved Hide resolved
import TokamakDOM

let document = JSObjectRef.global.document.object!
Expand Down