Skip to content

Commit

Permalink
Use onAppear/onDisappear in DOMEnvironment
Browse files Browse the repository at this point in the history
  • Loading branch information
MaxDesiatov committed Jul 2, 2020
1 parent 1776434 commit af498ac
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 3 deletions.
2 changes: 1 addition & 1 deletion Sources/TokamakCore/Views/View.swift
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ protocol GroupView: ParentView {}
views is made in the reconciler in `TokamakCore` based on their `body` type, host views have body
type `Never`. `ViewDeferredToRenderer` allows renderers to override that per-platform and render
host views as composite by providing their own `deferredBody` implementation.
*/
*/
public protocol ViewDeferredToRenderer {
var deferredBody: AnyView { get }
}
Expand Down
21 changes: 20 additions & 1 deletion Sources/TokamakDOM/Environment/DOMEnvironment.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,33 @@
// See the License for the specific language governing permissions and
// limitations under the License.

import JavaScriptKit
import TokamakCore

/// This is effectively a singleton, but a mounted `DOMEnvironment` is assumed to be a singleton
/// too. It can't be declared as a property of `DOMEnvironment` as you can't modify it from within
/// `body` callbacks.
private var colorSchemeListener: JSClosure?

struct DOMEnvironment<V: View>: View {
@State var scheme: ColorScheme

let content: V

private let matchMedia =
JSObjectRef.global.window.object!.matchMedia!("(prefers-color-scheme: dark)").object!

var body: some View {
content.colorScheme(scheme)
content
.colorScheme(scheme)
.onAppear {
colorSchemeListener = JSClosure {
scheme = $0[0].object!.matches.boolean == true ? .dark : .light
return .undefined
}
_ = matchMedia.addEventListener!("change", colorSchemeListener!)
}.onDisappear {
_ = matchMedia.removeEventListener!("change", colorSchemeListener!)
}
}
}
2 changes: 1 addition & 1 deletion Sources/TokamakDemo/EnvironmentDemo.swift
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ struct EnvironmentDemo: View {
if let font = font {
return Text("ColorScheme is \(scheme), font is \(font)")
} else {
return Text("`font` environment not set.")
return Text("ColorScheme is \(scheme), `font` environment not set.")
}
}
}

0 comments on commit af498ac

Please sign in to comment.