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
2 changes: 1 addition & 1 deletion .swift-version
Original file line number Diff line number Diff line change
@@ -1 +1 @@
wasm-DEVELOPMENT-SNAPSHOT-2020-06-12-a
wasm-DEVELOPMENT-SNAPSHOT-2020-07-14-a
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
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
8 changes: 4 additions & 4 deletions Sources/TokamakDOM/Views/SecureField.swift
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,10 @@ extension SecureField: ViewDeferredToRenderer where Label == Text {
], listeners: [
"keypress": { event in if event.key == "Enter" { proxy.onCommit() } },
"input": { event in
if let newValue = event.target.object?.value.string {
proxy.textBinding.wrappedValue = newValue
}
},
if let newValue = event.target.object?.value.string {
proxy.textBinding.wrappedValue = newValue
}
},
carson-katri marked this conversation as resolved.
Show resolved Hide resolved
]))
}
}
8 changes: 4 additions & 4 deletions Sources/TokamakDOM/Views/TextField.swift
Original file line number Diff line number Diff line change
Expand Up @@ -44,10 +44,10 @@ extension TextField: ViewDeferredToRenderer where Label == Text {
"blur": { _ in proxy.onEditingChanged(false) },
"keypress": { event in if event.key == "Enter" { proxy.onCommit() } },
"input": { event in
if let newValue = event.target.object?.value.string {
proxy.textBinding.wrappedValue = newValue
}
},
if let newValue = event.target.object?.value.string {
proxy.textBinding.wrappedValue = newValue
}
},
]))
}
}
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 @@ -67,5 +67,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