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 ColorScheme environment #136

Merged
merged 41 commits into from
Aug 2, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
41 commits
Select commit Hold shift + click to select a range
9313bf1
Add ColorScheme environment
MaxDesiatov Jun 30, 2020
ce432b7
Fix wrong colorScheme computed property type
MaxDesiatov Jun 30, 2020
a3c69b6
Add DOMEnvironment view with colorScheme state
MaxDesiatov Jul 1, 2020
1776434
Fix linter line length warning
MaxDesiatov Jul 1, 2020
af498ac
Use onAppear/onDisappear in DOMEnvironment
MaxDesiatov Jul 2, 2020
26f7ef5
Merge branch 'main' of github.com:maxdesiatov/Tokamak into color-scheme
MaxDesiatov Jul 21, 2020
f792a9f
Generalize environment updates
MaxDesiatov Jul 21, 2020
855a438
Environment propagation fix in progress
MaxDesiatov Jul 21, 2020
a59f9bc
Button styles work
diskzero Jul 24, 2020
e9a94c1
Button style work
SemitoneGene Jul 24, 2020
95db246
Add basic `ButtonStyle` implementation
MaxDesiatov Jul 25, 2020
8962950
Fix pointer events
MaxDesiatov Jul 26, 2020
ab46418
Merge branch 'main' of github.com:swiftwasm/Tokamak into color-scheme
MaxDesiatov Jul 26, 2020
c8b0f05
Fix compilation errors after merge
MaxDesiatov Jul 26, 2020
af6d2db
Fix build error on macOS
MaxDesiatov Jul 26, 2020
d0dca18
Fix linter warning
MaxDesiatov Jul 26, 2020
77ef826
Fix super.update call crashes
MaxDesiatov Jul 26, 2020
cbd3e2c
Merge branch 'main' of github.com:swiftwasm/Tokamak into color-scheme
MaxDesiatov Jul 27, 2020
938d951
Add `DefaultApp` type to simplify DOMRenderer.init
MaxDesiatov Jul 27, 2020
74b4c66
Merge branch 'domrenderer-defaultapp' of github.com:swiftwasm/Tokamak…
MaxDesiatov Jul 27, 2020
22accdb
Add ColorSchemeObserver, App._colorSchemePublisher
MaxDesiatov Jul 27, 2020
c08b40d
Hook `colorScheme` observer to the environment
MaxDesiatov Jul 27, 2020
58c45c7
Fix build errors
MaxDesiatov Jul 27, 2020
94432a5
Remove redundant print statements
MaxDesiatov Jul 27, 2020
921f2c5
Merge branch 'main' of github.com:swiftwasm/Tokamak into buttonstyles
MaxDesiatov Jul 29, 2020
8acdf2a
Fix host view environment propagation
MaxDesiatov Jul 29, 2020
5b437e9
Fix unused result warnings
MaxDesiatov Jul 29, 2020
f0cf159
Unify environment updates in MountedElement.init
MaxDesiatov Jul 30, 2020
62de63a
Set appearance to `none` for non-default styles
MaxDesiatov Jul 30, 2020
5f275e1
Tweak button style reset CSS
MaxDesiatov Jul 30, 2020
fe183c3
Merge branch 'buttonstyles' of github.com:swiftwasm/Tokamak into colo…
MaxDesiatov Jul 30, 2020
20a0e82
Assorted cleanups to reduce the diff
MaxDesiatov Jul 30, 2020
feb9d18
Retain observer's `JSClosure`
MaxDesiatov Jul 30, 2020
edb5e70
Merge branch 'main' of github.com:swiftwasm/Tokamak into color-scheme
MaxDesiatov Aug 1, 2020
e8044db
Merge branch 'main' of github.com:swiftwasm/Tokamak into color-scheme
MaxDesiatov Aug 1, 2020
61632b8
Use `import CombineShim` in the observers code
MaxDesiatov Aug 1, 2020
08841e7
Merge branch 'main' of github.com:swiftwasm/Tokamak into color-scheme
MaxDesiatov Aug 1, 2020
c397eb6
Fix environment updates propagation to children
MaxDesiatov Aug 1, 2020
8dfaf78
Update EnvironmentDemo.swift
MaxDesiatov Aug 1, 2020
88f7e36
Address PR feedback
MaxDesiatov Aug 2, 2020
b3ad0e2
Revert `TokamakStaticHTML` changes
MaxDesiatov Aug 2, 2020
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
5 changes: 4 additions & 1 deletion Sources/TokamakCore/App/App.swift
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,10 @@ public protocol App: _TitledApp {
static func _launch(_ app: Self, _ rootEnvironment: EnvironmentValues)

/// Implemented by the renderer to update the `App` on `ScenePhase` changes
var _phasePublisher: CurrentValueSubject<ScenePhase, Never> { get }
var _phasePublisher: AnyPublisher<ScenePhase, Never> { get }
j-f1 marked this conversation as resolved.
Show resolved Hide resolved

/// Implemented by the renderer to update the `App` on `ColorScheme` changes
var _colorSchemePublisher: AnyPublisher<ColorScheme, Never> { get }

static func main()

Expand Down
6 changes: 5 additions & 1 deletion Sources/TokamakCore/App/_AnyApp.swift
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,11 @@ public struct _AnyApp: App {
fatalError("`title` cannot be set for `AnyApp`. Access underlying `app` value.")
}

public var _phasePublisher: CurrentValueSubject<ScenePhase, Never> {
public var _phasePublisher: AnyPublisher<ScenePhase, Never> {
fatalError("`_AnyApp` cannot monitor scenePhase. Access underlying `app` value.")
}

public var _colorSchemePublisher: AnyPublisher<ColorScheme, Never> {
fatalError("`_AnyApp` cannot monitor colorScheme. Access underlying `app` value.")
}
}
4 changes: 2 additions & 2 deletions Sources/TokamakCore/Environment/Environment.swift
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,8 @@ protocol EnvironmentReader {
case value(Value)
}

var content: Content
let keyPath: KeyPath<EnvironmentValues, Value>
private var content: Content
private let keyPath: KeyPath<EnvironmentValues, Value>
public init(_ keyPath: KeyPath<EnvironmentValues, Value>) {
content = .keyPath(keyPath)
self.keyPath = keyPath
Expand Down
1 change: 1 addition & 0 deletions Sources/TokamakCore/MountedViews/MountedHostView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ public final class MountedHostView<R: Renderer>: MountedElement<R> {
while let child = mountedChildren.first, let firstChild = childrenViews.first {
let newChild: MountedElement<R>
if firstChild.typeConstructorName == mountedChildren[0].view.typeConstructorName {
child.environmentValues = environmentValues
child.view = firstChild
child.updateEnvironment()
child.update(with: reconciler)
Expand Down
24 changes: 18 additions & 6 deletions Sources/TokamakCore/StackReconciler.swift
Original file line number Diff line number Diff line change
Expand Up @@ -94,12 +94,8 @@ public final class StackReconciler<R: Renderer> {

rootElement.mount(with: self)
if let mountedApp = rootElement as? MountedApp<R> {
app._phasePublisher.sink { [weak self] phase in
if mountedApp.environmentValues.scenePhase != phase {
mountedApp.environmentValues.scenePhase = phase
self?.queueUpdate(for: mountedApp)
}
}.store(in: &mountedApp.subscriptions)
setupSubscription(for: app._phasePublisher, to: \.scenePhase, of: mountedApp)
setupSubscription(for: app._colorSchemePublisher, to: \.colorScheme, of: mountedApp)
}
}

Expand Down Expand Up @@ -174,6 +170,22 @@ public final class StackReconciler<R: Renderer> {
}.store(in: &compositeElement.subscriptions)
}

private func setupSubscription<T: Equatable>(
for publisher: AnyPublisher<T, Never>,
to keyPath: WritableKeyPath<EnvironmentValues, T>,
of mountedApp: MountedApp<R>
) {
publisher.sink { [weak self, weak mountedApp] value in
guard
let mountedApp = mountedApp,
mountedApp.environmentValues[keyPath: keyPath] != value
else { return }

mountedApp.environmentValues[keyPath: keyPath] = value
self?.queueUpdate(for: mountedApp)
}.store(in: &mountedApp.subscriptions)
}

func render<T>(compositeElement: MountedCompositeElement<R>,
body bodyKeypath: ReferenceWritableKeyPath<MountedCompositeElement<R>, Any>,
result: KeyPath<MountedCompositeElement<R>, (Any) -> T>) -> T {
Expand Down
2 changes: 1 addition & 1 deletion Sources/TokamakCore/Tokens/Color.swift
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@

public struct Color: Hashable, Equatable {
// FIXME: This is not injected.
@Environment(\.accentColor) static var envAccentColor: Color?
@Environment(\.accentColor) static var envAccentColor

public enum RGBColorSpace {
case sRGB
Expand Down
37 changes: 37 additions & 0 deletions Sources/TokamakCore/Tokens/ColorScheme.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
// 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.

public enum ColorScheme: CaseIterable {
case dark
case light
}

public struct _ColorSchemeKey: EnvironmentKey {
public static var defaultValue: ColorScheme {
fatalError("\(self) must have a renderer-provided default value")
}
}

public extension EnvironmentValues {
var colorScheme: ColorScheme {
get { self[_ColorSchemeKey.self] }
set { self[_ColorSchemeKey.self] = newValue }
}
}

public extension View {
func colorScheme(_ colorScheme: ColorScheme) -> some View {
environment(\.colorScheme, colorScheme)
}
}
2 changes: 1 addition & 1 deletion Sources/TokamakCore/Views/Containers/DisclosureGroup.swift
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public struct DisclosureGroup<Label, Content>: View
@State var isExpanded: Bool = false
let isExpandedBinding: Binding<Bool>?

@Environment(\._outlineGroupStyle) var style: _OutlineGroupStyle
@Environment(\._outlineGroupStyle) var style

let label: Label
let content: () -> Content
Expand Down
2 changes: 1 addition & 1 deletion Sources/TokamakCore/Views/Containers/List.swift
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public struct List<SelectionValue, Content>: View
let selection: _Selection
let content: Content

@Environment(\.listStyle) var style: ListStyle
@Environment(\.listStyle) var style

public init(selection: Binding<Set<SelectionValue>>?, @ViewBuilder content: () -> Content) {
self.selection = .many(selection)
Expand Down
2 changes: 1 addition & 1 deletion Sources/TokamakCore/Views/NavigationView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public struct NavigationView<Content>: View where Content: View {
}

/// This is a helper class that works around absence of "package private" access control in Swift
public struct _NavigationViewProxy<Content: View> {
public struct _NavigationViewProxy<Content: View>: View {
public let subject: NavigationView<Content>

public init(_ subject: NavigationView<Content>) { self.subject = subject }
Expand Down
4 changes: 2 additions & 2 deletions Sources/TokamakCore/Views/Selectors/Picker.swift
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ public struct _PickerContainer<Label: View, SelectionValue: Hashable, Content: V
@Binding public var selection: SelectionValue
public let label: Label
public let content: Content
@Environment(\.pickerStyle) public var style: PickerStyle
@Environment(\.pickerStyle) public var style

public init(
selection: Binding<SelectionValue>,
Expand All @@ -36,7 +36,7 @@ public struct _PickerContainer<Label: View, SelectionValue: Hashable, Content: V
public struct _PickerElement: View {
public let valueIndex: Int?
public let content: AnyView
@Environment(\.pickerStyle) public var style: PickerStyle
@Environment(\.pickerStyle) public var style

public var body: Never {
neverBody("_PickerElement")
Expand Down
2 changes: 1 addition & 1 deletion Sources/TokamakCore/Views/Text/TextField.swift
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ public struct TextField<Label>: View where Label: View {
let textBinding: Binding<String>
let onEditingChanged: (Bool) -> ()
let onCommit: () -> ()
@Environment(\.textFieldStyle) var style: TextFieldStyle
@Environment(\.textFieldStyle) var style

public var body: Never {
neverBody("TextField")
Expand Down
2 changes: 1 addition & 1 deletion Sources/TokamakCore/Views/Toggle.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
public struct Toggle<Label>: View where Label: View {
@Binding var isOn: Bool
var label: Label
@Environment(\.toggleStyle) var toggleStyle: _AnyToggleStyle
@Environment(\.toggleStyle) var toggleStyle

public init(isOn: Binding<Bool>, label: () -> Label) {
_isOn = isOn
Expand Down
25 changes: 7 additions & 18 deletions Sources/TokamakDOM/App.swift → Sources/TokamakDOM/App/App.swift
Original file line number Diff line number Diff line change
Expand Up @@ -20,22 +20,6 @@ import JavaScriptKit
import TokamakCore
import TokamakStaticHTML

private enum ScenePhaseObserver {
static var publisher = CurrentValueSubject<ScenePhase, Never>(.active)

static func observe() {
_ = document.addEventListener!("visibilitychange", JSClosure { _ in
let visibilityState = document.visibilityState.string
if visibilityState == "visible" {
publisher.send(.active)
} else if visibilityState == "hidden" {
publisher.send(.background)
}
return .undefined
})
}
}

extension App {
/// The default implementation of `launch` for a `TokamakDOM` app.
///
Expand All @@ -60,6 +44,7 @@ extension App {
_ = body.appendChild!(div)

ScenePhaseObserver.observe()
ColorSchemeObserver.observe()
}

public static func _setTitle(_ title: String) {
Expand All @@ -69,7 +54,11 @@ extension App {
_ = head.appendChild!(titleTag)
}

public var _phasePublisher: CurrentValueSubject<ScenePhase, Never> {
ScenePhaseObserver.publisher
public var _phasePublisher: AnyPublisher<ScenePhase, Never> {
ScenePhaseObserver.publisher.eraseToAnyPublisher()
}

public var _colorSchemePublisher: AnyPublisher<ColorScheme, Never> {
ColorSchemeObserver.publisher.eraseToAnyPublisher()
}
}
33 changes: 33 additions & 0 deletions Sources/TokamakDOM/App/ColorSchemeObserver.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// 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.

import CombineShim
import JavaScriptKit

enum ColorSchemeObserver {
static var publisher = CurrentValueSubject<ColorScheme, Never>(
.init(matchMediaDarkScheme: matchMediaDarkScheme)
)

private static var closure: JSClosure?

static func observe() {
let closure = JSClosure {
publisher.value = .init(matchMediaDarkScheme: $0[0].object!)
return .undefined
}
_ = matchMediaDarkScheme.addEventListener!("change", closure)
Self.closure = closure
}
}
36 changes: 36 additions & 0 deletions Sources/TokamakDOM/App/ScenePhaseObserver.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
// 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.

import CombineShim
import JavaScriptKit

enum ScenePhaseObserver {
static var publisher = CurrentValueSubject<ScenePhase, Never>(.active)

private static var closure: JSClosure?

static func observe() {
let closure = JSClosure { _ in
let visibilityState = document.visibilityState.string
if visibilityState == "visible" {
publisher.send(.active)
} else if visibilityState == "hidden" {
publisher.send(.background)
}
return .undefined
}
_ = document.addEventListener!("visibilitychange", closure)
Self.closure = closure
}
}
6 changes: 6 additions & 0 deletions Sources/TokamakDOM/Core.swift
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,14 @@ public typealias RadioGroupPickerStyle = TokamakCore.RadioGroupPickerStyle
public typealias SegmentedPickerStyle = TokamakCore.SegmentedPickerStyle
public typealias WheelPickerStyle = TokamakCore.WheelPickerStyle

public typealias ToggleStyle = TokamakCore.ToggleStyle
public typealias ToggleStyleConfiguration = TokamakCore.ToggleStyleConfiguration

public typealias ButtonStyle = TokamakCore.ButtonStyle
public typealias ButtonStyleConfiguration = TokamakCore.ButtonStyleConfiguration
public typealias DefaultButtonStyle = TokamakCore.DefaultButtonStyle

public typealias ColorScheme = TokamakCore.ColorScheme

// MARK: Shapes

Expand Down
8 changes: 6 additions & 2 deletions Sources/TokamakDOM/DOMRenderer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ extension EnvironmentValues {
static var defaultEnvironment: Self {
var environment = EnvironmentValues()
environment[_ToggleStyleKey] = _AnyToggleStyle(DefaultToggleStyle())
environment[_ColorSchemeKey] = .init(matchMediaDarkScheme: matchMediaDarkScheme)
environment._defaultAppStorage = LocalStorage.standard
_DefaultSceneStorageProvider.default = SessionStorage.standard

Expand Down Expand Up @@ -54,8 +55,11 @@ private extension AnyView {
}
}

let log = JSObjectRef.global.console.object!.log.function!
let document = JSObjectRef.global.document.object!
let global = JSObjectRef.global
let window = global.window.object!
let matchMediaDarkScheme = window.matchMedia!("(prefers-color-scheme: dark)").object!
let log = global.console.object!.log.function!
let document = global.document.object!
let body = document.body.object!
let head = document.head.object!

Expand Down
21 changes: 21 additions & 0 deletions Sources/TokamakDOM/Styles/ColorScheme.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// 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.

import JavaScriptKit

extension ColorScheme {
init(matchMediaDarkScheme: JSObjectRef) {
self = matchMediaDarkScheme.matches.boolean == true ? .dark : .light
}
}
19 changes: 17 additions & 2 deletions Sources/TokamakDemo/EnvironmentDemo.swift
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,28 @@ struct EnvironmentObjectDemo: View {
}
}

extension ColorScheme: CustomStringConvertible {
public var description: String {
switch self {
case .dark: return "dark"
case .light: return "light"
@unknown default: return "unknown"
}
}
}

struct EnvironmentDemo: View {
@Environment(\.font) var font: Font?
@Environment(\.colorScheme) var colorScheme

@Environment(\.font) var font
@EnvironmentObject var testEnv: TestEnvironment

var body: some View {
VStack {
Text(font == nil ? "`font` environment not set." : "\(String(describing: font!))")
Text("`colorScheme` is \(colorScheme.description)")
if let font = font {
Text("`font` environment is \(String(describing: font))")
}
Text(testEnv.envTest)
EnvironmentObjectDemo()
}
Expand Down
Loading