diff --git a/Package.resolved b/Package.resolved index 78b23b74d..69928b8ed 100644 --- a/Package.resolved +++ b/Package.resolved @@ -1,5 +1,5 @@ { - "originHash" : "3266d17691afb98c2b7b4b4294f7ff5724343a4ac95bbd2ac6189b77230085f9", + "originHash" : "84b82640662870fda9d5e16c14fb949e0dfecf56dd78a121d6414932d03658b3", "pins" : [ { "identity" : "darwinprivateframeworks", @@ -7,7 +7,7 @@ "location" : "https://github.com/OpenSwiftUIProject/DarwinPrivateFrameworks.git", "state" : { "branch" : "main", - "revision" : "d46803e009851e31ff8190fcf2cfc9dee3ed1e0e" + "revision" : "491c68d2970fc5d4379dac36137744faa25e2d7f" } }, { diff --git a/Package.swift b/Package.swift index 850cac21b..07febf9e0 100644 --- a/Package.swift +++ b/Package.swift @@ -155,6 +155,7 @@ let renderBoxCondition = envBoolValue("RENDERBOX", default: buildForDarwinPlatfo let linkCoreUI = envBoolValue("LINK_COREUI", default: buildForDarwinPlatform) let linkCoreSVG = envBoolValue("LINK_CORESVG", default: buildForDarwinPlatform) let linkSFSymbols = envBoolValue("LINK_SFSYMBOLS", default: buildForDarwinPlatform) +let linkSymbols = envBoolValue("LINK_SYMBOLS", default: buildForDarwinPlatform) let linkFeatureFlags = envBoolValue("LINK_FEATUREFLAGS", default: buildForDarwinPlatform) let linkBacklightServices = envBoolValue("LINK_BACKLIGHTSERVICES", default: buildForDarwinPlatform) let linkGestures = envBoolValue("LINK_GESTURES", default: buildForDarwinPlatform && releaseVersion >= 2025) @@ -269,6 +270,12 @@ if linkSFSymbols { ) } +if linkSymbols { + sharedSwiftSettings.append( + .define("OPENSWIFTUI_LINK_SYMBOLS", .when(platforms: [.iOS, .macOS, .visionOS])) + ) +} + if linkFeatureFlags { sharedSwiftSettings.append( .define("OPENSWIFTUI_LINK_FEATUREFLAGS", .when(platforms: [.iOS, .macOS, .visionOS])) @@ -433,6 +440,16 @@ extension Target { ) } + func addSymbolsSettings() { + dependencies.append( + .product( + name: "Symbols", + package: "DarwinPrivateFrameworks", + condition: .when(platforms: [.iOS, .macOS, .visionOS]) + ) + ) + } + func addFeatureFlagsSettings() { dependencies.append( .product( @@ -953,6 +970,11 @@ if linkSFSymbols { openSwiftUICoreTarget.addSFSymbolsSettings() } +if linkSymbols { + openSwiftUITarget.addSymbolsSettings() + openSwiftUITestTarget.addSymbolsSettings() +} + if linkFeatureFlags { openSwiftUICoreTarget.addFeatureFlagsSettings() openSwiftUITarget.addFeatureFlagsSettings() @@ -970,7 +992,7 @@ if useLocalDeps { .package(path: "../OpenRenderBox"), .package(path: "../OpenObservation"), ] - if attributeGraphCondition || renderBoxCondition || linkCoreUI || linkCoreSVG || linkSFSymbols || linkFeatureFlags || linkBacklightServices || linkGestures { + if attributeGraphCondition || renderBoxCondition || linkCoreUI || linkCoreSVG || linkSFSymbols || linkSymbols || linkFeatureFlags || linkBacklightServices || linkGestures { dependencies.append(.package(path: "../DarwinPrivateFrameworks")) } package.dependencies += dependencies @@ -982,7 +1004,7 @@ if useLocalDeps { .package(url: "https://github.com/OpenSwiftUIProject/OpenRenderBox", branch: "main"), .package(url: "https://github.com/OpenSwiftUIProject/OpenObservation", branch: "main"), ] - if attributeGraphCondition || renderBoxCondition || linkCoreUI || linkCoreSVG || linkSFSymbols || linkFeatureFlags || linkGestures { + if attributeGraphCondition || renderBoxCondition || linkCoreUI || linkCoreSVG || linkSFSymbols || linkSymbols || linkFeatureFlags || linkGestures { dependencies.append(.package(url: "https://github.com/OpenSwiftUIProject/DarwinPrivateFrameworks.git", branch: "main")) } package.dependencies += dependencies diff --git a/Sources/OpenSwiftUI/Render/SymbolEffect/SymbolEffectAPI.swift b/Sources/OpenSwiftUI/Render/SymbolEffect/SymbolEffectAPI.swift new file mode 100644 index 000000000..662115621 --- /dev/null +++ b/Sources/OpenSwiftUI/Render/SymbolEffect/SymbolEffectAPI.swift @@ -0,0 +1,680 @@ +// +// SymbolEffectAPI.swift +// OpenSwiftUI +// +// Audited for 6.5.4 +// Status: Complete +// ID: 1E42BCA1B3AC632454FB5BE9F835FBCE (SwiftUI) + +#if OPENSWIFTUI_LINK_SYMBOLS +import OpenAttributeGraphShims +@_spi(Private) public import OpenSwiftUICore +@_spi(Private) public import Symbols + +// MARK: - View + symbolEffect + +@available(OpenSwiftUI_v5_0, *) +extension View { + /// Returns a new view with a symbol effect added to it. + /// + /// The following example adds a repeating pulse effect to two + /// symbol images: + /// + /// VStack { + /// Image(systemName: "bolt.slash.fill") + /// Image(systemName: "folder.fill.badge.person.crop") + /// } + /// .symbolEffect(.pulse) + /// + /// - Parameters: + /// - effect: A symbol effect to add to the view. Existing effects + /// added by ancestors of the view are preserved, but may be + /// overridden by the new effect. Added effects will be applied + /// to the ``Image`` views contained by the child view. + /// - isActive: whether the effect is active or inactive. + /// + /// - Returns: a copy of the view with a symbol effect added. + @_alwaysEmitIntoClient + nonisolated public func symbolEffect( + _ effect: T, + options: SymbolEffectOptions = .default, + isActive: Bool = true + ) -> some View where T: IndefiniteSymbolEffect, T: Symbols.SymbolEffect { + modifier(_IndefiniteSymbolEffectModifier( + effect: effect, options: options, isActive: isActive)) + } + + /// Returns a new view with a symbol effect added to it. + /// + /// The following example adds a bounce effect to two symbol + /// images, the animation will play each time `counter` changes: + /// + /// VStack { + /// Image(systemName: "bolt.slash.fill") + /// Image(systemName: "folder.fill.badge.person.crop") + /// } + /// .symbolEffect(.bounce, value: counter) + /// + /// - Parameters: + /// - effect: A symbol effect to add to the view. Existing effects + /// added by ancestors of the view are preserved, but may be + /// overridden by the new effect. Added effects will be applied + /// to the ``Image`` views contained by the child view. + /// - value: the value to monitor for changes, the animation is + /// triggered each time the value changes. + /// + /// - Returns: a copy of the view with a symbol effect added. + @_alwaysEmitIntoClient + nonisolated public func symbolEffect( + _ effect: T, + options: SymbolEffectOptions = .default, + value: U + ) -> some View where T: DiscreteSymbolEffect, T: Symbols.SymbolEffect, U: Equatable { + modifier(_DiscreteSymbolEffectModifier( + effect: effect, options: options, value: value)) + } +} + +@_spi(Private) +@available(OpenSwiftUI_v6_0, *) +extension View { + @_alwaysEmitIntoClient + nonisolated public func symbolEffect( + _ effect: T, + options: SymbolEffectOptions = .default, + when condition: Bool + ) -> some View where T: DiscreteSymbolEffect, T: Symbols.SymbolEffect { + modifier(_ConditionalSymbolEffectModifier( + effect: effect, options: options, condition: condition)) + } +} + +// MARK: - _IndefiniteSymbolEffectModifier + +@available(OpenSwiftUI_v5_0, *) +@frozen +public struct _IndefiniteSymbolEffectModifier: ViewModifier, PrimitiveViewModifier, _GraphInputsModifier { + @usableFromInline + var config: SymbolEffectConfiguration + + @usableFromInline + var options: SymbolEffectOptions + + @usableFromInline + var isActive: Bool + + @_alwaysEmitIntoClient + init( + effect: T, + options: SymbolEffectOptions, + isActive: Bool + ) where T: IndefiniteSymbolEffect, T: Symbols.SymbolEffect { + self.config = effect.configuration + self.options = options + self.isActive = isActive + } + + public static func _makeInputs(modifier: _GraphValue, inputs: inout _GraphInputs) { + inputs.environment = Attribute( + EffectEnvironment( + modifier: modifier.value, + environment: inputs.environment, + identifier: Int(makeUniqueID()) + ) + ) + } + + private struct EffectEnvironment: Rule, AsyncAttribute { + @Attribute var modifier: _IndefiniteSymbolEffectModifier + @Attribute var environment: EnvironmentValues + let identifier: Int + + var value: EnvironmentValues { + var environment = environment + guard modifier.isActive, + let effect = _SymbolEffect(config: modifier.config, options: modifier.options) + else { + return environment + } + environment.appendSymbolEffect(effect, for: identifier) + return environment + } + } +} + +@available(*, unavailable) +extension _IndefiniteSymbolEffectModifier: Sendable {} + +// MARK: - _DiscreteSymbolEffectModifier + +@available(OpenSwiftUI_v5_0, *) +@frozen +public struct _DiscreteSymbolEffectModifier: ViewModifier, PrimitiveViewModifier, _GraphInputsModifier where T: Equatable { + @usableFromInline + var config: SymbolEffectConfiguration + + @usableFromInline + var options: SymbolEffectOptions + + @usableFromInline + var value: T + + @_alwaysEmitIntoClient + init( + effect: U, + options: SymbolEffectOptions, + value: T + ) where U: DiscreteSymbolEffect, U: Symbols.SymbolEffect { + config = effect.configuration + self.options = options + self.value = value + } + + public static func _makeInputs(modifier: _GraphValue, inputs: inout _GraphInputs) { + inputs.environment = Attribute( + EffectEnvironment( + modifier: modifier.value, + environment: inputs.environment, + identifier: Int(makeUniqueID()) + ) + ) + } + + private struct EffectEnvironment: Rule, AsyncAttribute { + @Attribute var modifier: _DiscreteSymbolEffectModifier + @Attribute var environment: EnvironmentValues + let identifier: Int + + var value: EnvironmentValues { + var environment = environment + let modifier = modifier + guard let effect = _SymbolEffect( + config: modifier.config, + options: modifier.options, + trigger: .value(AnyEquatable(modifier.value)) + ) else { + return environment + } + environment.appendSymbolEffect(effect, for: identifier) + return environment + } + } +} + +@available(*, unavailable) +extension _DiscreteSymbolEffectModifier: Sendable {} + +// MARK: - _ConditionalSymbolEffectModifier + +@available(OpenSwiftUI_v6_0, *) +@frozen +public struct _ConditionalSymbolEffectModifier: ViewModifier, PrimitiveViewModifier, _GraphInputsModifier { + @usableFromInline + var config: SymbolEffectConfiguration + + @usableFromInline + var options: SymbolEffectOptions + + @usableFromInline + var condition: Bool + + @_alwaysEmitIntoClient + init( + effect: U, + options: SymbolEffectOptions, + condition: Bool + ) where U: DiscreteSymbolEffect, U: Symbols.SymbolEffect { + config = effect.configuration + self.options = options + self.condition = condition + } + + public static func _makeInputs(modifier: _GraphValue, inputs: inout _GraphInputs) { + inputs.environment = Attribute( + EffectEnvironment( + modifier: modifier.value, + environment: inputs.environment, + identifier: Int(makeUniqueID()) + ) + ) + } + + private struct EffectEnvironment: Rule, AsyncAttribute { + @Attribute var modifier: _ConditionalSymbolEffectModifier + @Attribute var environment: EnvironmentValues + let identifier: Int + + var value: EnvironmentValues { + var environment = environment + let modifier = modifier + guard let effect = _SymbolEffect( + config: modifier.config, + options: modifier.options, + trigger: .condition(modifier.condition) + ) else { + return environment + } + environment.appendSymbolEffect(effect, for: identifier) + return environment + } + } +} + +@available(*, unavailable) +extension _ConditionalSymbolEffectModifier: Sendable {} + +// MARK: - SymbolEffectTransition + +@available(OpenSwiftUI_v5_0, *) +extension Transition where Self == SymbolEffectTransition { + /// Creates a transition that applies the provided effect to symbol + /// images within the inserted or removed view hierarchy. Other + /// views are unaffected by this transition. + /// + /// - Parameter effect: the symbol effect value. + /// + /// - Returns: a new transition. + @_alwaysEmitIntoClient + @MainActor + @preconcurrency + public static func symbolEffect( + _ effect: T, + options: SymbolEffectOptions = .default + ) -> SymbolEffectTransition where T: Symbols.SymbolEffect, T: TransitionSymbolEffect { + SymbolEffectTransition(effect: effect, options: options) + } + + /// A transition that applies the default symbol effect transition + /// to symbol images within the inserted or removed view hierarchy. + /// Other views are unaffected by this transition. + @_alwaysEmitIntoClient + @MainActor + @preconcurrency + public static var symbolEffect: SymbolEffectTransition { + symbolEffect(.automatic) + } +} + +/// Creates a transition that applies the Appear or Disappear +/// symbol animation to symbol images within the inserted or +/// removed view hierarchy. +/// +/// Other views are unaffected by this transition. +@available(OpenSwiftUI_v5_0, *) +@frozen +@MainActor +@preconcurrency +public struct SymbolEffectTransition: Transition { + @usableFromInline + var config: SymbolEffectConfiguration + + @usableFromInline + var options: SymbolEffectOptions + + @_alwaysEmitIntoClient + public init( + effect: T, + options: SymbolEffectOptions + ) where T: Symbols.SymbolEffect, T: TransitionSymbolEffect { + config = effect.configuration + self.options = options + } + + public func body(content: Content, phase: TransitionPhase) -> some View { + var effect: SymbolEffect? + if let hidden = _SymbolEffect.HiddenConfiguration(config, hidden: !phase.isIdentity) { + effect = SymbolEffect( + base: _SymbolEffect(.hidden(hidden), options: _SymbolEffect.Options(options)) + ) + } + return content.modifier(_SymbolEffectModifier(effect: effect)) + } + + public static let properties = TransitionProperties(hasMotion: true) + + public func _makeContentTransition(transition: inout _Transition_ContentTransition) { + switch transition.operation { + case .effects: + guard let hidden = _SymbolEffect.HiddenConfiguration(config, hidden: true) else { + return + } + let effect = ContentTransition.Effect( + type: ContentTransition.EffectType( + type: .symbolAppearDisappear, + arg0: .int(hidden.transitionFlags.rawValue), + arg1: .float(_SymbolEffect.Options(options).speed) + ) + ) + transition.result = .effects([effect]) + case .hasContentTransition: + if _SymbolEffect.HiddenConfiguration(config, hidden: true) != nil { + transition.result = .bool(true) + } + } + } +} + +@available(*, unavailable) +extension SymbolEffectTransition: Sendable {} + +// MARK: - ContentTransition + symbolEffect + +@available(OpenSwiftUI_v5_0, *) +extension ContentTransition { + /// Creates a content transition that applies the symbol Replace + /// animation to symbol images that it is applied to. + /// + /// - Parameter effect: the animation configuration value. + /// + /// - Returns: a new content transition. + public static func symbolEffect( + _ effect: T, + options: SymbolEffectOptions = .default + ) -> ContentTransition where T: ContentTransitionSymbolEffect, T: Symbols.SymbolEffect { + guard let config = _SymbolEffect.ReplaceConfiguration(effect.configuration, options: options) else { + return .default + } + return ContentTransition(storage: .symbolReplace(config)) + } + + /// A content transition that applies the default symbol effect + /// transition to symbol images within the inserted or removed view + /// hierarchy. Other views are unaffected by this transition. + @_alwaysEmitIntoClient + public static var symbolEffect: ContentTransition { + symbolEffect(.automatic) + } +} + +// MARK: - WiggleSymbolEffect + Angle + +extension WiggleSymbolEffect { + /// Returns a copy of the effect requesting an animation that moves + /// back and forth along an axis with the passed in angle. + @available(OpenSwiftUI_v6_0, *) + @_alwaysEmitIntoClient + public func custom(angle: Angle) -> WiggleSymbolEffect { + custom(angle: angle.degrees) + } +} + +// MARK: - _SymbolEffect + Symbols + +extension _SymbolEffect { + fileprivate init?(config: SymbolEffectConfiguration, options: SymbolEffectOptions) { + let storage: Storage + switch config.effect { + case let .pulse(effect): + var value = PulseConfiguration() + value.layered = effect.isLayered ?? true + storage = .pulse(value) + case let .bounce(effect): + storage = .bounce(BounceConfiguration( + effect, + isContinuous: options.repeat == nil || options.prefersContinuous, + trigger: nil + )) + case let .variableColor(effect): + storage = .variableColor(VariableColorConfiguration(effect, trigger: nil)) + case let .scale(effect): + var value = ScaleConfiguration() + value.layered = effect.isLayered ?? true + if let isUp = effect.isUp { + value.level = isUp ? .up : .down + } + storage = .scale(value) + case let .appear(effect): + var value = HiddenConfiguration() + value.layered = effect.isLayered ?? true + if let isUp = effect.isUp { + value.flags = isUp ? .down : .up + } + value.isHidden = true + storage = .hidden(value) + case let .disappear(effect): + var value = HiddenConfiguration() + value.layered = effect.isLayered ?? true + if let isUp = effect.isUp { + value.flags = isUp ? .up : .down + } + value.isHidden = true + storage = .hidden(value) + case let .wiggle(effect): + storage = .wiggle(WiggleConfiguration( + effect, + isContinuous: options.repeat == nil || options.prefersContinuous, + trigger: nil + )) + case let .rotate(effect): + storage = .rotate(RotateConfiguration( + effect, + isContinuous: options.repeat == nil || options.prefersContinuous, + trigger: nil + )) + case let .breathe(effect): + storage = .breathe(BreatheConfiguration(effect, trigger: nil)) + default: + return nil + } + self.init(storage, options: Options(options)) + } + + fileprivate init?( + config: SymbolEffectConfiguration, + options: SymbolEffectOptions, + trigger: _SymbolEffect.Trigger + ) { + let storage: Storage + switch config.effect { + case let .pulse(effect): + var value = PulseConfiguration() + value.layered = effect.isLayered ?? true + value.trigger = trigger + storage = .pulse(value) + case let .bounce(effect): + storage = .bounce(BounceConfiguration( + effect, + isContinuous: options.repeat != nil && options.prefersContinuous, + trigger: trigger + )) + case let .variableColor(effect): + storage = .variableColor(VariableColorConfiguration(effect, trigger: trigger)) + case let .wiggle(effect): + storage = .wiggle(WiggleConfiguration( + effect, + isContinuous: options.repeat != nil && options.prefersContinuous, + trigger: trigger + )) + case let .rotate(effect): + storage = .rotate(RotateConfiguration( + effect, + isContinuous: options.repeat != nil && options.prefersContinuous, + trigger: trigger + )) + case let .breathe(effect): + storage = .breathe(BreatheConfiguration(effect, trigger: trigger)) + default: + return nil + } + self.init(storage, options: Options(options)) + } +} + +// MARK: - _SymbolEffect.Options + Symbols + +extension _SymbolEffect.Options { + fileprivate init(_ options: SymbolEffectOptions) { + self.init() + switch options.repeat { + case let .count(count): + repeatCount = Float(count) + case .indefinite: + repeatCount = .infinity + default: + break + } + repeatDelay = options.repeatDelay.map { Float($0) } + speed = Float(options.speed) + } +} + +// MARK: - _SymbolEffect.HiddenConfiguration + Symbols + +extension _SymbolEffect.HiddenConfiguration { + fileprivate init?(_ config: SymbolEffectConfiguration, hidden: Bool) { + self.init() + switch config.effect { + case let .appear(effect): + layered = effect.isLayered ?? true + if let isUp = effect.isUp { + flags = isUp ? .down : .up + } + case let .disappear(effect): + layered = effect.isLayered ?? true + if let isUp = effect.isUp { + flags = isUp ? .up : .down + } + case .automatic: + break + default: + return nil + } + isHidden = hidden + } +} + +// MARK: - _SymbolEffect.ReplaceConfiguration + Symbols + +extension _SymbolEffect.ReplaceConfiguration { + fileprivate init?(_ config: SymbolEffectConfiguration, options: SymbolEffectOptions) { + switch config.effect { + case let .replace(effect): + self.init( + effect, + options: options, + allowMagic: effect.style == nil && isLinkedOnOrAfter(.v6) + ) + case .automatic: + self.init() + speed = Float(options.speed) + case let .magicReplace(effect): + self.init(effect.fallback, options: options, allowMagic: true) + default: + return nil + } + } +} + +// MARK: - _SymbolEffect.BounceConfiguration + Symbols + +extension _SymbolEffect.BounceConfiguration { + fileprivate init(_ effect: BounceSymbolEffect, isContinuous: Bool, trigger: _SymbolEffect.Trigger?) { + self.init() + layered = effect.isLayered ?? true + if isContinuous { + flags.insert(.continuous) + } + if let isUp = effect.isUp { + flags.insert(isUp ? .up : .down) + } + self.trigger = trigger + } +} + +// MARK: - _SymbolEffect.VariableColorConfiguration + Symbols + +extension _SymbolEffect.VariableColorConfiguration { + fileprivate init(_ effect: VariableColorSymbolEffect, trigger: _SymbolEffect.Trigger?) { + self.init() + if effect.isReversing == true { + flags.insert(.reversing) + } + if effect.isIterative == true { + flags.insert(.iterative) + } + if effect.hasReveal == true { + flags.insert(.hideInactiveLayers) + } + self.trigger = trigger + } +} + +// MARK: - _SymbolEffect.WiggleConfiguration + Symbols + +extension _SymbolEffect.WiggleConfiguration { + fileprivate init(_ effect: WiggleSymbolEffect, isContinuous: Bool, trigger: _SymbolEffect.Trigger?) { + self.init() + layered = effect.isLayered ?? true + if isContinuous { + flags.insert(.continuous) + } + switch effect.style { + case let .rotational(forward): + flags.insert(.rotational) + flags.insert(forward ? .forward : .backward) + case let .linear(degrees): + angle = .degrees(degrees) + case let .localized(forward): + flags.insert(.localized) + flags.insert(forward ? .forward : .backward) + appliesRTL = true + default: + break + } + self.trigger = trigger + } +} + +// MARK: - _SymbolEffect.RotateConfiguration + Symbols + +extension _SymbolEffect.RotateConfiguration { + fileprivate init(_ effect: RotateSymbolEffect, isContinuous: Bool, trigger: _SymbolEffect.Trigger?) { + self.init() + layered = effect.isLayered ?? true + if isContinuous { + flags.insert(.continuous) + } + if let isClockwise = effect.isClockwise { + flags.insert(isClockwise ? .clockwise : .counterClockwise) + } + self.trigger = trigger + } +} + +// MARK: - _SymbolEffect.BreatheConfiguration + Symbols + +extension _SymbolEffect.BreatheConfiguration { + fileprivate init(_ effect: BreatheSymbolEffect, trigger: _SymbolEffect.Trigger?) { + self.init() + layered = effect.isLayered ?? true + if case .scale = effect.style { + flags.insert(.onlyScale) + } + self.trigger = trigger + } +} + +// MARK: - _SymbolEffect.ReplaceConfiguration + ReplaceSymbolEffect + +extension _SymbolEffect.ReplaceConfiguration { + fileprivate init(_ effect: ReplaceSymbolEffect, options: SymbolEffectOptions, allowMagic: Bool) { + self.init() + layered = effect.isLayered ?? true + speed = Float(options.speed) + switch effect.style { + case .downUp: + flags.insert(.down) + case .upUp: + flags.insert(.up) + case .offUp: + flags.insert(.offUp) + default: + break + } + if !allowMagic { + flags.insert(.noSlashes) + flags.insert(.noBadges) + } + } +} +#endif diff --git a/Tests/OpenSwiftUITests/Render/SymbolEffectAPITests.swift b/Tests/OpenSwiftUITests/Render/SymbolEffectAPITests.swift new file mode 100644 index 000000000..bafb1b7f1 --- /dev/null +++ b/Tests/OpenSwiftUITests/Render/SymbolEffectAPITests.swift @@ -0,0 +1,416 @@ +// +// SymbolEffectAPITests.swift +// OpenSwiftUITests + +#if OPENSWIFTUI_LINK_SYMBOLS +import OpenAttributeGraphShims +@_spi(Private) @testable import OpenSwiftUI +@_spi(ForOpenSwiftUIOnly) @_spi(Private) @testable import OpenSwiftUICore +import OpenSwiftUITestsSupport +@_spi(Private) import Symbols +import Testing + +@MainActor +struct SymbolEffectAPITests { + @Suite(.disabled(if: attributeGraphVendor == .oag)) + @MainActor + struct Modifiers { + @Test + func indefiniteActivationPreservesInheritedEffects() throws { + var environment = EnvironmentValues() + environment.appendSymbolEffect(_SymbolEffect(.none), for: 7) + let modifier = _IndefiniteSymbolEffectModifier( + effect: PulseSymbolEffect.pulse.wholeSymbol, + options: .speed(2), + isActive: false + ) + try SymbolEffectAPITests.withEnvironment(modifier, environment: environment) { attribute, output in + #expect(output.value.symbolEffects == environment.symbolEffects) + var active = modifier + active.isActive = true + attribute.value = active + let effects = output.value.symbolEffects + #expect(effects.count == 2) + #expect(effects.first == environment.symbolEffects.first) + let effect = try #require(effects.last) + guard case let .pulse(pulse) = effect.effect.storage else { + Issue.record("Expected a pulse effect") + return + } + #expect(pulse.layered == false) + #expect(pulse.trigger == nil) + #expect(effect.effect.options.speed == 2) + active.options = .speed(3) + attribute.value = active + #expect(output.value.symbolEffects.last?.identifier == effect.identifier) + #expect(output.value.symbolEffects.last?.effect.options.speed == 3) + } + } + + @Test(arguments: [ + BounceSymbolEffect.bounce.configuration, + WiggleSymbolEffect.wiggle.configuration, + RotateSymbolEffect.rotate.configuration, + ]) + func continuousDefaultsDependOnTrigger(configuration: SymbolEffectConfiguration) throws { + let effect = Effect(configuration: configuration) + let cases: [(SymbolEffectOptions.RepeatOption?, Bool, Bool, Bool)] = [ + (nil, false, true, false), + (nil, true, true, false), + (.count(3), false, false, false), + (.count(3), true, true, true), + (.indefinite, false, false, false), + (.indefinite, true, true, true), + ] + for (repetition, prefersContinuous, expectedIndefinite, expectedDiscrete) in cases { + var options = SymbolEffectOptions.default + options.repeat = repetition + options.prefersContinuous = prefersContinuous + let indefinite = _IndefiniteSymbolEffectModifier(effect: effect, options: options, isActive: true) + let discrete = _DiscreteSymbolEffectModifier(effect: effect, options: options, value: 42) + try SymbolEffectAPITests.withEnvironment(indefinite) { _, output in + let value = try #require(output.value.symbolEffects.first?.effect) + #expect(continuous(value) == expectedIndefinite) + } + try SymbolEffectAPITests.withEnvironment(discrete) { _, output in + let value = try #require(output.value.symbolEffects.first?.effect) + #expect(continuous(value) == expectedDiscrete) + } + } + } + + @Test + func scalePreservesOptionalDirectionAndLayering() throws { + let cases: [(ScaleSymbolEffect, Int32, Bool)] = [ + (.scale, 0, true), + (.scale.up.wholeSymbol, 1, false), + (.scale.down.byLayer, -1, true), + ] + for (effect, level, layered) in cases { + let modifier = _IndefiniteSymbolEffectModifier(effect: effect, options: .default, isActive: true) + try SymbolEffectAPITests.withEnvironment(modifier) { _, output in + guard case let .scale(value) = try #require(output.value.symbolEffects.first?.effect.storage) else { + Issue.record("Expected a scale effect") + return + } + #expect(value.level.rawValue == level) + #expect(value.layered == layered) + } + } + } + + @Test + func indefiniteAppearAndDisappearUseHiddenState() throws { + let cases: [(SymbolEffectConfiguration, UInt32, Bool)] = [ + (AppearSymbolEffect.appear.configuration, 0, true), + (AppearSymbolEffect.appear.up.configuration, 2, true), + (AppearSymbolEffect.appear.down.wholeSymbol.configuration, 3, false), + (DisappearSymbolEffect.disappear.configuration, 0, true), + (DisappearSymbolEffect.disappear.up.configuration, 3, true), + (DisappearSymbolEffect.disappear.down.wholeSymbol.configuration, 2, false), + ] + for (configuration, flags, layered) in cases { + let modifier = _IndefiniteSymbolEffectModifier( + effect: Effect(configuration: configuration), options: .default, isActive: true + ) + try SymbolEffectAPITests.withEnvironment(modifier) { _, output in + guard case let .hidden(value) = try #require(output.value.symbolEffects.first?.effect.storage) else { + Issue.record("Expected a hidden effect") + return + } + #expect(value.flags.rawValue == flags) + #expect(value.layered == layered) + #expect(value.isHidden) + } + } + } + + @Test(arguments: [ + PulseSymbolEffect.pulse.configuration, + BounceSymbolEffect.bounce.configuration, + VariableColorSymbolEffect.variableColor.configuration, + WiggleSymbolEffect.wiggle.configuration, + RotateSymbolEffect.rotate.configuration, + BreatheSymbolEffect.breathe.configuration, + ]) + func triggersReachStorage(configuration: SymbolEffectConfiguration) throws { + let effect = Effect(configuration: configuration) + let discrete = _DiscreteSymbolEffectModifier(effect: effect, options: .default, value: 42) + try SymbolEffectAPITests.withEnvironment(discrete) { attribute, output in + let initial = try #require(output.value.symbolEffects.first?.effect) + #expect(trigger(initial) == .value(AnyEquatable(42))) + var changed = discrete + changed.value = 43 + attribute.value = changed + let updated = try #require(output.value.symbolEffects.first?.effect) + #expect(trigger(updated) == .value(AnyEquatable(43))) + } + let conditional = _ConditionalSymbolEffectModifier(effect: effect, options: .default, condition: false) + try SymbolEffectAPITests.withEnvironment(conditional) { attribute, output in + let initial = try #require(output.value.symbolEffects.first?.effect) + #expect(trigger(initial) == .condition(false)) + var changed = conditional + changed.condition = true + attribute.value = changed + let updated = try #require(output.value.symbolEffects.first?.effect) + #expect(trigger(updated) == .condition(true)) + } + } + + @Test(arguments: [ + ScaleSymbolEffect.scale.configuration, + AppearSymbolEffect.appear.configuration, + DisappearSymbolEffect.disappear.configuration, + ReplaceSymbolEffect.replace.configuration, + AutomaticSymbolEffect.automatic.configuration, + ReplaceSymbolEffect.replace.magic(fallback: .replace).configuration, + ]) + func discreteRejectsUnsupportedEffects(configuration: SymbolEffectConfiguration) { + let modifier = _DiscreteSymbolEffectModifier( + effect: Effect(configuration: configuration), options: .default, value: 1 + ) + SymbolEffectAPITests.withEnvironment(modifier) { _, output in + #expect(output.value.symbolEffects.isEmpty) + } + } + + @Test(arguments: [ + ReplaceSymbolEffect.replace.configuration, + AutomaticSymbolEffect.automatic.configuration, + ReplaceSymbolEffect.replace.magic(fallback: .replace).configuration, + ]) + func indefiniteRejectsUnsupportedEffects(configuration: SymbolEffectConfiguration) { + let modifier = _IndefiniteSymbolEffectModifier( + effect: Effect(configuration: configuration), options: .default, isActive: true + ) + SymbolEffectAPITests.withEnvironment(modifier) { _, output in + #expect(output.value.symbolEffects.isEmpty) + } + } + + @Test + func optionsPreserveRepeatAndFloatConversions() throws { + let cases: [(SymbolEffectOptions.RepeatOption?, Double?, Double, Float?, Float?, Float)] = [ + (nil, nil, 1, nil, nil, 1), + (.count(0), 0, 0, 0, 0, 0), + (.count(-2), -0.25, -2, -2, -0.25, -2), + (.count(16_777_217), 0.25, 2.5, 16_777_216, 0.25, 2.5), + (.indefinite, .infinity, .infinity, .infinity, .infinity, .infinity), + ] + for (repetition, delay, speed, expectedCount, expectedDelay, expectedSpeed) in cases { + var options = SymbolEffectOptions.default + options.repeat = repetition + options.repeatDelay = delay + options.speed = speed + let modifier = _DiscreteSymbolEffectModifier(effect: PulseSymbolEffect.pulse, options: options, value: 0) + try SymbolEffectAPITests.withEnvironment(modifier) { _, output in + let result = try #require(output.value.symbolEffects.first?.effect.options) + #expect(result.repeatCount == expectedCount) + #expect(result.repeatDelay == expectedDelay) + #expect(result.speed == expectedSpeed) + } + } + } + + @Test + func stylesMapToRenderOptions() throws { + let cases: [(SymbolEffectConfiguration, UInt32, Bool)] = [ + (.init(effect: .bounce(.bounce.up.wholeSymbol)), 1, false), + (.init(effect: .bounce(.bounce.down.byLayer)), 2, true), + (.init(effect: .rotate(.rotate.clockwise.wholeSymbol)), 1, false), + (.init(effect: .rotate(.rotate.counterClockwise.byLayer)), 2, true), + (.init(effect: .breathe(.breathe.plain)), 1, true), + (.init(effect: .breathe(.breathe.pulse.wholeSymbol)), 0, false), + ] + for (configuration, flags, layered) in cases { + let modifier = _DiscreteSymbolEffectModifier(effect: Effect(configuration: configuration), options: .default, value: 0) + try SymbolEffectAPITests.withEnvironment(modifier) { _, output in + switch try #require(output.value.symbolEffects.first?.effect.storage) { + case let .bounce(value): + #expect(value.flags.rawValue == flags) + #expect(value.layered == layered) + case let .rotate(value): + #expect(value.flags.rawValue == flags) + #expect(value.layered == layered) + case let .breathe(value): + #expect(value.flags.rawValue == flags) + #expect(value.layered == layered) + default: + Issue.record("Unexpected effect kind") + } + } + } + } + + @Test + func variableColorMapsIndependentFlags() throws { + let modifier = _DiscreteSymbolEffectModifier( + effect: VariableColorSymbolEffect.variableColor.iterative.reversing.hideInactiveLayers, + options: .default, value: 0 + ) + try SymbolEffectAPITests.withEnvironment(modifier) { _, output in + guard case let .variableColor(value) = try #require(output.value.symbolEffects.first?.effect.storage) else { + Issue.record("Expected a variable color effect") + return + } + #expect(value.flags.rawValue == 0xB) + } + } + + @Test + func wiggleConvertsAnglesAndLocalizedDirections() throws { + let cases: [(Symbols.WiggleSymbolEffect.WiggleStyle?, UInt32, Double?, Bool)] = [ + (nil, 0, nil, false), + (.rotational(true), 0x13, nil, false), + (.rotational(false), 0x23, nil, false), + (.linear(90), 0, .pi / 2, false), + (.localized(true), 0x21, nil, true), + (.localized(false), 0x11, nil, true), + ] + for (style, flags, radians, rtl) in cases { + var effect = WiggleSymbolEffect.wiggle.wholeSymbol + effect.style = style + var environment = EnvironmentValues() + environment.layoutDirection = .rightToLeft + let modifier = _DiscreteSymbolEffectModifier(effect: effect, options: .default, value: 0) + try SymbolEffectAPITests.withEnvironment(modifier, environment: environment) { _, output in + guard case let .wiggle(value) = try #require(output.value.symbolEffects.first?.effect.storage) else { + Issue.record("Expected a wiggle effect") + return + } + #expect(value.flags.rawValue == flags) + #expect(value.angle?.radians == radians) + #expect(value.layered == false) + #expect(value.appliesRTL == false) + if rtl { #expect(value.flags.contains(.localized)) } + } + } + } + + private func continuous(_ effect: _SymbolEffect) -> Bool? { + switch effect.storage { + case let .bounce(value): value.flags.contains(.continuous) + case let .wiggle(value): value.flags.contains(.continuous) + case let .rotate(value): value.flags.contains(.continuous) + default: nil + } + } + + private func trigger(_ effect: _SymbolEffect) -> _SymbolEffect.Trigger? { + switch effect.storage { + case let .pulse(value): value.trigger + case let .bounce(value): value.trigger + case let .variableColor(value): value.trigger + case let .wiggle(value): value.trigger + case let .rotate(value): value.trigger + case let .breathe(value): value.trigger + default: nil + } + } + } + + @Test + func hiddenTransitionMapsDirectionAndLayering() throws { + let cases: [(SymbolEffectConfiguration, UInt32)] = [ + (AppearSymbolEffect.appear.configuration, 0), + (AppearSymbolEffect.appear.up.configuration, 2), + (AppearSymbolEffect.appear.down.wholeSymbol.configuration, 0x13), + (DisappearSymbolEffect.disappear.up.configuration, 3), + (DisappearSymbolEffect.disappear.down.wholeSymbol.configuration, 0x12), + (AutomaticSymbolEffect.automatic.configuration, 0), + ] + for (configuration, flags) in cases { + let value = SymbolEffectTransition(effect: Effect(configuration: configuration), options: .speed(2.5)) + var transition = _Transition_ContentTransition(operation: .effects(style: .default, size: .zero), result: .none) + value._makeContentTransition(transition: &transition) + guard case let .effects(effects) = transition.result else { + Issue.record("Expected symbol transition effects") + continue + } + let effect = try #require(effects.first) + #expect(effects.count == 1) + #expect(effect.type.type == .symbolAppearDisappear) + #expect(effect.type.arg0 == .int(flags)) + #expect(effect.type.arg1 == .float(2.5)) + transition = .init(operation: .hasContentTransition, result: .none) + value._makeContentTransition(transition: &transition) + guard case let .bool(result) = transition.result else { + Issue.record("Expected a content transition") + continue + } + #expect(result) + } + } + + @Test(arguments: [Semantics.v5, .v6]) + func replacementStylesAndMagic(semantics: Semantics) throws { + try semantics.test { + let cases: [(SymbolEffectConfiguration, UInt32, Bool)] = [ + (AutomaticSymbolEffect.automatic.configuration, 0, true), + (ReplaceSymbolEffect.replace.configuration, semantics == .v6 ? 0 : 0x60, true), + (ReplaceSymbolEffect.replace.downUp.configuration, 0x62, true), + (ReplaceSymbolEffect.replace.upUp.wholeSymbol.configuration, 0x63, false), + (ReplaceSymbolEffect.replace.offUp.configuration, 0x64, true), + (ReplaceSymbolEffect.replace.magic(fallback: .replace.offUp.wholeSymbol).configuration, 4, false), + ] + for (configuration, flags, layered) in cases { + let transition = ContentTransition.symbolEffect(Effect(configuration: configuration), options: .speed(2.5)) + guard case let .symbolReplace(value) = transition.storage else { + Issue.record("Expected a symbol replacement transition") + continue + } + #expect(value.flags.rawValue == flags) + #expect(value.layered == layered) + #expect(value.speed == 2.5) + } + } + } + + @Test + func unsupportedTransitionsPreserveFallbacks() { + let effect = Effect(configuration: PulseSymbolEffect.pulse.configuration) + #expect(ContentTransition.symbolEffect(effect) == .default) + let value = SymbolEffectTransition(effect: effect, options: .default) + var transition = _Transition_ContentTransition(operation: .effects(style: .default, size: .zero), result: .none) + value._makeContentTransition(transition: &transition) + guard case .none = transition.result else { + Issue.record("Expected the unsupported transition to retain its result") + return + } + transition = .init(operation: .hasContentTransition, result: .bool(false)) + value._makeContentTransition(transition: &transition) + guard case let .bool(result) = transition.result else { + Issue.record("Expected the unsupported transition to retain its result") + return + } + #expect(result == false) + } + + private struct Effect: Symbols.SymbolEffect, IndefiniteSymbolEffect, DiscreteSymbolEffect, + TransitionSymbolEffect, ContentTransitionSymbolEffect { + var configuration: SymbolEffectConfiguration + } + + private static func withEnvironment( + _ modifier: Modifier, + environment: EnvironmentValues = .init(), + _ body: (Attribute, Attribute) throws -> Void + ) rethrows { + let graph = Graph(shared: Graph()) + let subgraph = Subgraph(graph: graph) + defer { subgraph.invalidate() } + let current = Subgraph.current + Subgraph.current = subgraph + defer { Subgraph.current = current } + let attribute = Attribute(value: modifier) + var inputs = _GraphInputs( + time: Attribute(value: .zero), + phase: Attribute(value: .init()), + environment: Attribute(value: environment), + transaction: Attribute(value: .init()) + ) + Modifier._makeInputs(modifier: _GraphValue(attribute), inputs: &inputs) + try body(attribute, inputs.environment) + } +} +#endif