file_path
stringlengths
3
280
file_language
stringclasses
66 values
content
stringlengths
1
1.04M
repo_name
stringlengths
5
92
repo_stars
int64
0
154k
repo_description
stringlengths
0
402
repo_primary_language
stringclasses
108 values
developer_username
stringlengths
1
25
developer_name
stringlengths
0
30
developer_company
stringlengths
0
82
Sources/SwiftComponent/Internal/AreOrderedSetsDuplicates.swift
Swift
// Copyright (c) 2024 Point-Free, Inc. // https://github.com/pointfreeco/swift-composable-architecture/blob/main/LICENSE import Foundation import OrderedCollections @inlinable func areOrderedSetsDuplicates<T>(_ lhs: OrderedSet<T>, _ rhs: OrderedSet<T>) -> Bool { guard lhs.count == rhs.count else { return false } return withUnsafePointer(to: lhs) { lhsPointer in withUnsafePointer(to: rhs) { rhsPointer in memcmp(lhsPointer, rhsPointer, MemoryLayout<OrderedSet<T>>.size) == 0 || lhs == rhs } } }
yonaskolb/SwiftComponent
16
Where architecture meets tooling
Swift
yonaskolb
Yonas Kolb
Sources/SwiftComponent/Internal/CodeEditor.swift
Swift
import Foundation import SwiftParser import SwiftSyntax class CodeParser { let originalSource: String let syntax: SourceFileSyntax init(source: String) { originalSource = source syntax = Parser.parse(source: source) } var modelSource: Codeblock? { syntax.getStruct(type: "ComponentModel").map(Codeblock.init) } var viewSource: Codeblock? { syntax.getStruct(type: "ComponentView").map(Codeblock.init) } var componentSource: Codeblock? { syntax.getStruct(type: "Component").map(Codeblock.init) } } class CodeRewriter: SyntaxRewriter { var blocks: [Codeblock] init(blocks: [Codeblock]) { self.blocks = blocks } func rewrite(_ tree: SourceFileSyntax) -> SourceFileSyntax { let updated = visit(tree) return updated } override func visit(_ node: MemberBlockSyntax) -> MemberBlockSyntax { for block in blocks { if block.syntax.id == node.id { var parser = Parser(block.source) return MemberBlockSyntax.parse(from: &parser) } } return node } } struct Codeblock { let syntax: SyntaxProtocol var source: String { didSet { changed = true } } var changed = false init(syntax: SyntaxProtocol) { if let block: MemberBlockSyntax = syntax.getChild() { self.source = block.description self.syntax = block } else { self.source = "" self.syntax = syntax } } } extension CodeParser { func getState() -> String? { guard let structSyntax = syntax.getStruct(id: "State"), let block = structSyntax.children(viewMode: .sourceAccurate).compactMap( { $0.as(MemberBlockSyntax.self) }).first, let declarationList = block.children(viewMode: .sourceAccurate).compactMap( { $0.as(MemberBlockItemListSyntax.self) }).first else { return nil } let string = declarationList.children(viewMode: .sourceAccurate) .map { $0.description } .joined(separator: "") .trimmingCharacters(in: .newlines) return string// + "\n\n" + declarationList.debugDescription(includeChildren: true, includeTrivia: false) } } extension SyntaxProtocol { func getStruct(type: String) -> StructDeclSyntax? { getChild { structSyntax in guard let typeClause: InheritedTypeListSyntax = structSyntax.getChild(), let _: IdentifierTypeSyntax = typeClause.getChild(compare: { $0.name.text == type }) else { return false } return true } } func getStruct(id: String) -> StructDeclSyntax? { getChild { $0.name.description == id } } func getChild<ChildType: SyntaxProtocol>(compare: (ChildType) -> Bool = { _ in true }) -> ChildType? { for child in children(viewMode: .sourceAccurate) { if let structSyntax = child.as(ChildType.self), compare(structSyntax) { return structSyntax } else if let childState = child.getChild(compare: compare) { return childState } } return nil } }
yonaskolb/SwiftComponent
16
Where architecture meets tooling
Swift
yonaskolb
Yonas Kolb
Sources/SwiftComponent/Internal/ComponentDescription.swift
Swift
@_implementationOnly import Runtime struct ComponentDescription: Equatable, Codable { var model: ModelInfo var component: ComponentInfo } extension ComponentDescription { init<ComponentType: Component>(type: ComponentType.Type) throws { func getType(_ type: Any.Type) throws -> TypeDescription { let info = try typeInfo(of: type) switch info.kind { case .enum: let cases: [TypeDescription.Case] = try info.cases.map { caseType in var payloads: [String] = [] if let payload = caseType.payloadType { let payloadType = try typeInfo(of: payload) switch payloadType.kind { case .tuple: payloads = payloadType.properties .map { String(describing: $0.type).sanitizedType } case .struct: payloads = [payloadType.name.sanitizedType] default: payloads = [payloadType.name.sanitizedType] } } return .init(name: caseType.name, payloads: payloads) } return .enumType(cases) case .struct: let properties: [TypeDescription.Property] = info.properties .map { var name = $0.name // remove underscores added by property wrappers and macros if name.hasPrefix("_") { name = String(name.dropFirst()) } return TypeDescription.Property(name: name, type: String(describing: $0.type).sanitizedType) } .filter { !$0.name.hasPrefix("$") } // remove $ prefixes like registrationRegistrar return .structType(properties) case .never: return .never default: return .structType(try info.properties.map { .init(name: $0.name, type: try typeInfo(of: $0.type).name) }) } } let model = ModelInfo( name: ComponentType.Model.name, connections: try getType(ComponentType.Model.Connections.self), state: try getType(ComponentType.Model.State.self), action: try getType(ComponentType.Model.Action.self), input: try getType(ComponentType.Model.Input.self), route: try getType(ComponentType.Model.Route.self), output: try getType(ComponentType.Model.Output.self) ) let component = ComponentInfo( name: String(describing: ComponentType.self), tests: ComponentType.tests.map { $0.testName }, states: ComponentType.snapshots.map(\.name) ) self.init(model: model, component: component) } } struct ModelInfo: Equatable, Codable { var name: String var connections: TypeDescription var state: TypeDescription var action: TypeDescription var input: TypeDescription var route: TypeDescription var output: TypeDescription } struct ViewInfo: Equatable, Codable { var name: String var routes: [String] } struct ComponentInfo: Equatable, Codable { var name: String var tests: [String] var states: [String] } enum TypeDescription: Equatable, Codable { case enumType([Case]) case structType([Property]) case never var isNever: Bool { switch self { case .never: return true case .structType(let properties): return properties.isEmpty case .enumType(let cases): return cases.isEmpty } } struct Property: Equatable, Codable { var name: String var type: String } struct Case: Equatable, Codable { var name: String var payloads: [String] } } fileprivate extension String { var sanitizedType: String { self .replaceType("Optional", replacement: "$1?") .replaceType("ModelConnection", regex: "ModelConnection<(.*), (.*)>", replacement: "$2") .replaceType("EmbeddedComponentConnection", regex: "EmbeddedComponentConnection<(.*), (.*)>", replacement: "$2") .replaceType("PresentedComponentConnection", regex: "PresentedComponentConnection<(.*), (.*)>", replacement: "$2") .replaceType("PresentedCaseComponentConnection", regex: "PresentedCaseComponentConnection<(.*), (.*), (.*)>", replacement: "$2") .replaceType("ComponentRoute", replacement: "$1") .replaceType("Resource", replacement: "$1") .replaceType("Array", replacement: "[$1]") } func replaceType(_ type: String, replacement: String = "$1") -> String { if hasPrefix("\(type)<") && hasSuffix(">") { return self.replacingOccurrences(of: "^\(type)<(.*)>", with: replacement, options: .regularExpression).sanitizedType } else { return self } } func replaceType(_ type: String, regex: String? = nil, replacement: String = "$1") -> String { if hasPrefix("\(type)<") && hasSuffix(">") { return self.replacingOccurrences(of: regex ?? "^\(type)<(.*)>", with: replacement, options: .regularExpression).sanitizedType } else { return self } } }
yonaskolb/SwiftComponent
16
Where architecture meets tooling
Swift
yonaskolb
Yonas Kolb
Sources/SwiftComponent/Internal/Core.swift
Swift
import Foundation import CustomDump extension String { func indent(by indent: Int) -> String { let indentation = String(repeating: " ", count: indent) return indentation + self.replacingOccurrences(of: "\n", with: "\n\(indentation)") } var quoted: String { "\"\(self)\""} } public func dumpToString(_ value: Any, maxDepth: Int = .max) -> String { var string = "" customDump(value, to: &string, maxDepth: maxDepth) return string } func dumpLine(_ value: Any) -> String { //TODO: do custom dumping to one line var string = dumpToString(value) // remove type wrapper string = string.replacingOccurrences(of: #"^\S*\(\s*([\s\S]*?)\s*\)"#, with: "$1", options: .regularExpression) // remove newlines string = string.replacingOccurrences(of: #"\n\s*( )"#, with: "$1", options: .regularExpression) return string } struct StateDump { static func diff(_ old: Any, _ new: Any) -> [String]? { guard let diff = CustomDump.diff(old, new) else { return nil } let lines = diff.components(separatedBy: "\n") return lines .map { line in if line.hasSuffix(",") || line.hasSuffix("(") { return String(line.dropLast()) } else if line.hasSuffix(" [") { return String(line.dropLast(2)) } else { return line } } .filter { let actual = $0 .trimmingCharacters(in: CharacterSet(charactersIn: "+")) .trimmingCharacters(in: CharacterSet(charactersIn: "-")) .trimmingCharacters(in: .whitespaces) return actual != ")" && actual != "]" } } } /// returns true if lhs and rhs are equatable and are equal func areMaybeEqual(_ lhs: Any, _ rhs: Any) -> Bool { if let lhs = lhs as? any Equatable { if areEqual(lhs, rhs) { return true } } return false } func areEqual<A: Equatable>(_ lhs: A, _ rhs: Any) -> Bool { lhs == (rhs as? A) }
yonaskolb/SwiftComponent
16
Where architecture meets tooling
Swift
yonaskolb
Yonas Kolb
Sources/SwiftComponent/Internal/Enum.swift
Swift
import Foundation struct EnumCase { let name: String let values: [String: Any] } func getEnumCase<T>(_ enumValue: T) -> EnumCase { let reflection = Mirror(reflecting: enumValue) guard reflection.displayStyle == .enum, let associated = reflection.children.first else { return EnumCase(name: "\(enumValue)", values: [:]) } let valuesChildren = Mirror(reflecting: associated.value).children var values = [String: Any]() for case let item in valuesChildren where item.label != nil { values[item.label!] = item.value } return EnumCase(name: associated.label!, values: values) }
yonaskolb/SwiftComponent
16
Where architecture meets tooling
Swift
yonaskolb
Yonas Kolb
Sources/SwiftComponent/Internal/ExampleComponent.swift
Swift
import Foundation import SwiftUI @ComponentModel struct ExampleModel { struct Connections { let child = Connection<ExampleChildModel>(output: Input.child) let connectedChild = Connection<ExampleChildModel>(output: Input.child) .dependency(\.uuid, value: .incrementing) .connect(state: \.child) let presentedChild = Connection<ExampleChildModel>(output: Input.child) .connect(state: \.presentedChild) let caseChild = Connection<ExampleChildModel>(output: Input.child) .connect(state: \.destination, case: \.child) } struct State: Equatable { var name: String var loading: Bool = false var date = Date() var presentedChild: ExampleChildModel.State? var child: ExampleChildModel.State = .init(name: "child") var destination: Destination? @Resource var resource: String? } enum Action: Equatable { case tap(Int) case open } enum Destination: Equatable { case child(ExampleChildModel.State) } enum Output { case finished case unhandled } enum Input { case child(ExampleChildModel.Output) } func appear() async { await task("get thing") { state.loading = false } } func handle(action: Action) async { switch action { case .tap(_): state.date = dependencies.date() if #available(iOS 16, macOS 13, *) { try? await dependencies.continuousClock.sleep(for: .seconds(1)) } output(.finished) case .open: state.presentedChild = .init(name: state.name) // route(to: Route.open, state: .init(name: state.name)) // .dependency(\.uuid, .constant(.init(1))) } } func handle(input: Input) async { switch input { case .child(.finished): state.presentedChild = nil print("Child finished") } } } struct ExampleView: ComponentView { var model: ViewModel<ExampleModel> var view: some View { if #available(iOS 16, macOS 13, *) { NavigationStack { VStack { Text(model.name) ProgressView().opacity(model.loading ? 1 : 0) Text(model.date.formatted()) button(.tap(1), "Tap") button(.open, "Open") ExampleChildView(model: model.connections.connectedChild) } .navigationDestination(item: model.presentedModel(\.presentedChild), destination: ExampleChildView.init) } } } } @ComponentModel struct ExampleChildModel { struct State: Equatable { var name: String } enum Action: Equatable { case tap(Int) case close } enum Output { case finished } func handle(action: Action) async { switch action { case .tap(let int): state.name += int.description if #available(iOS 16, macOS 13, *) { try? await dependencies.continuousClock.sleep(for: .seconds(1)) } output(.finished) case .close: dismiss() } } func handle(event: Event) { event.forModel(ExampleChildModel.self) { event in switch event { case .output(let output): switch output { case .finished: break } default: break } } } } struct ExampleChildView: ComponentView { var model: ViewModel<ExampleChildModel> var view: some View { VStack { Text(model.name) button(.tap(4)) { Text(model.dependencies.uuid().uuidString) } button(.close, "Close") } } } struct ExampleComponent: Component, PreviewProvider { typealias Model = ExampleModel static func view(model: ViewModel<ExampleModel>) -> some View { ExampleView(model: model) } static var preview = Snapshot(state: .init(name: "Main")) static var tests: Tests { Test("Set date") { let date = Date().addingTimeInterval(10000) Step.action(.tap(2)) .expectState { $0.date = date } .dependency(\.date, .constant(date)) Step.snapshot("tapped") } Test("Fill out") { Step.snapshot("empty", tags: ["empty"]) Step.appear() Step.binding(\.name, "test") .expectTask("get thing", successful: true) .expectState(\.name, "invalid") .expectState(\.date, Date()) Step.snapshot("filled", tags: ["featured"]) } Test("Open child") { Step.action(.open) Step.connection(\.connectedChild) { Step.action(.tap(4)) } } } }
yonaskolb/SwiftComponent
16
Where architecture meets tooling
Swift
yonaskolb
Yonas Kolb
Sources/SwiftComponent/Internal/Export.swift
Swift
import Foundation import Dependencies import CasePaths @_exported import Dependencies @_exported import CasePaths @_exported import SwiftUINavigation @_exported import IdentifiedCollections #if canImport(Observation) @_exported import Observation #endif #if canImport(Perception) @_exported import Perception #endif
yonaskolb/SwiftComponent
16
Where architecture meets tooling
Swift
yonaskolb
Yonas Kolb
Sources/SwiftComponent/Internal/KeyPath.swift
Swift
import Foundation @_implementationOnly import Runtime extension KeyPath { // swift 5.8 has a debugDescription on KeyPath, and even works with getters, but it doesn't work with index lookups // We can use mirror as a fallback but it doesn't work with getters or indices // TODO: enable Item.array[0].string to be "array[0].string" somehow. For now just do array.string var propertyName: String? { #if swift(>=5.8) if #available(iOS 16.4, macOS 13.3, *) { // Is in format "\State.standup.name" so drop the slash and type let debugDescriptionResult = debugDescription .dropFirst() // drop slash .split(separator: ".") .filter { !($0.hasPrefix("<computed") && $0.hasSuffix(">")) } .dropFirst() // drop State .joined(separator: ".") .replacingOccurrences(of: ".subscript(_: Int)", with: "") .replacingOccurrences(of: "<Unknown>", with: "_") .replacingOccurrences(of: #"^\$"#, with: "", options: .regularExpression) // drop leading $ .replacingOccurrences(of: #"\?$"#, with: "", options: .regularExpression) // drop trailing ? // If debugDescription parsing resulted in empty string (likely due to computed properties), // fall back to Runtime-based approach if !debugDescriptionResult.isEmpty { return debugDescriptionResult } else { return mirrorPropertyName } } else { return mirrorPropertyName } #else mirrorPropertyName #endif } private var mirrorPropertyName: String? { guard let offset = MemoryLayout<Root>.offset(of: self) else { return nil } guard let info = try? typeInfo(of: Root.self) else { return nil } func getPropertyName(for info: TypeInfo, baseOffset: Int, path: [String]) -> String? { for property in info.properties { // Make sure to check the type as well as the offset. In the case of // something like \Foo.bar.baz, if baz is the first property of bar, they // will have the same offset since it will be at the top (offset 0). if property.offset == offset - baseOffset && property.type == Value.self { return (path + [property.name]).joined(separator: ".") } guard let propertyTypeInfo = try? typeInfo(of: property.type) else { continue } let trueOffset = baseOffset + property.offset let byteRange = trueOffset..<(trueOffset + propertyTypeInfo.size) if byteRange.contains(offset) { // The property is not this property but is within the byte range used by the value. // So check its properties for the value at the offset. return getPropertyName( for: propertyTypeInfo, baseOffset: property.offset + baseOffset, path: path + [property.name] ) } } return nil } return getPropertyName(for: info, baseOffset: 0, path: []) } }
yonaskolb/SwiftComponent
16
Where architecture meets tooling
Swift
yonaskolb
Yonas Kolb
Sources/SwiftComponent/Internal/Source.swift
Swift
import Foundation public struct Source: Hashable { public static func == (lhs: Source, rhs: Source) -> Bool { lhs.file.description == rhs.file.description && lhs.line == rhs.line } public let file: StaticString public let line: UInt public func hash(into hasher: inout Hasher) { hasher.combine(file.description) hasher.combine(line) } public static func capture(file: StaticString = #filePath, line: UInt = #line) -> Self { Source(file: file, line: line) } }
yonaskolb/SwiftComponent
16
Where architecture meets tooling
Swift
yonaskolb
Yonas Kolb
Sources/SwiftComponent/Internal/ViewHelpers.swift
Swift
import Foundation import SwiftUI extension View { func interactiveBackground() -> some View { contentShape(Rectangle()) } func eraseToAnyView() -> AnyView { AnyView(self) } }
yonaskolb/SwiftComponent
16
Where architecture meets tooling
Swift
yonaskolb
Yonas Kolb
Sources/SwiftComponent/Macros.swift
Swift
import Observation @attached(extension, conformances: ComponentModel) @attached(memberAttribute) @attached(member, names: arbitrary) public macro ComponentModel() = #externalMacro(module: "SwiftComponentMacros", type: "ComponentModelMacro") @attached(extension, conformances: Observable, ObservableState) @attached(member, names: named(_$id), named(_$observationRegistrar), named(_$willModify)) @attached(memberAttribute) public macro ObservableState() = #externalMacro(module: "SwiftComponentMacros", type: "ObservableStateMacro") @attached(accessor, names: named(init), named(get), named(set)) @attached(peer, names: prefixed(_)) public macro ObservationStateTracked() = #externalMacro(module: "SwiftComponentMacros", type: "ObservationStateTrackedMacro") @attached(accessor, names: named(willSet)) public macro ObservationStateIgnored() = #externalMacro(module: "SwiftComponentMacros", type: "ObservationStateIgnoredMacro") /// Wraps a property with ``ResourceState`` and observes it. /// /// Use this macro instead of ``ResourceState`` when you adopt the ``ObservableState()`` /// macro, which is incompatible with property wrappers like ``ResourceState``. @attached(accessor, names: named(init), named(get), named(set)) @attached(peer, names: prefixed(`$`), prefixed(_)) public macro Resource() = #externalMacro(module: "SwiftComponentMacros", type: "ResourceMacro")
yonaskolb/SwiftComponent
16
Where architecture meets tooling
Swift
yonaskolb
Yonas Kolb
Sources/SwiftComponent/ModelContext.swift
Swift
import Foundation import SwiftUI import CasePaths import Dependencies @dynamicMemberLookup public class ModelContext<Model: ComponentModel> { weak var store: ComponentStore<Model>! init(store: ComponentStore<Model>) { self.store = store } @MainActor public var state: Model.State { store.state } @MainActor public subscript<Value>(dynamicMember keyPath: WritableKeyPath<Model.State, Value>) -> Value { get { store.state[keyPath: keyPath] } set { // TODO: can't capture source location // https://forums.swift.org/t/add-default-parameter-support-e-g-file-to-dynamic-member-lookup/58490/2 store.mutate(keyPath, value: newValue, source: nil) } } // so we can access read only properties @MainActor public subscript<Value>(dynamicMember keyPath: KeyPath<Model.State, Value>) -> Value { store.state[keyPath: keyPath] } }
yonaskolb/SwiftComponent
16
Where architecture meets tooling
Swift
yonaskolb
Yonas Kolb
Sources/SwiftComponent/Models.swift
Swift
import Foundation //typealias SimpleModel<State, Action, Environment> = ViewModel<SimpleComponentModel<State, Action, Environment>> //struct SimpleComponentModel<State, Output, Environment>: ComponentModel { // // typealias State = State // typealias Action = Output // typealias Output = Output // typealias Environment = Environment // // static func handle(action: Action, model: Model) async { // model.output(action) // } //} public protocol ActionOutput: ComponentModel where Action == Output {} public extension ActionOutput { @MainActor func handle(action: Action) async { await outputAsync(action) } }
yonaskolb/SwiftComponent
16
Where architecture meets tooling
Swift
yonaskolb
Yonas Kolb
Sources/SwiftComponent/Observation/ObservableState.swift
Swift
// Copyright (c) 2024 Point-Free, Inc. // https://github.com/pointfreeco/swift-composable-architecture/blob/main/LICENSE #if canImport(Perception) import Foundation /// A type that emits notifications to observers when underlying data changes. /// /// Conforming to this protocol signals to other APIs that the value type supports observation. /// However, applying the ``ObservableState`` protocol by itself to a type doesn’t add observation /// functionality to the type. Instead, always use the ``ObservableState()`` macro when adding /// observation support to a type. #if !os(visionOS) public protocol ObservableState: Perceptible { var _$id: ObservableStateID { get } mutating func _$willModify() } #else public protocol ObservableState: Observable { var _$id: ObservableStateID { get } mutating func _$willModify() } #endif /// A unique identifier for a observed value. public struct ObservableStateID: Equatable, Hashable, Sendable { @usableFromInline var location: UUID { get { self.storage.id.location } set { if !isKnownUniquelyReferenced(&self.storage) { self.storage = Storage(id: self.storage.id) } self.storage.id.location = newValue } } private var storage: Storage private init(storage: Storage) { self.storage = storage } public init() { self.init(storage: Storage(id: .location(UUID()))) } public static func == (lhs: Self, rhs: Self) -> Bool { lhs.storage === rhs.storage || lhs.storage.id == rhs.storage.id } public func hash(into hasher: inout Hasher) { hasher.combine(self.storage.id) } @inlinable public static func _$id<T>(for value: T) -> Self { (value as? any ObservableState)?._$id ?? Self() } @inlinable public static func _$id(for value: some ObservableState) -> Self { value._$id } public func _$tag(_ tag: Int) -> Self { Self(storage: Storage(id: .tag(tag, self.storage.id))) } @inlinable public mutating func _$willModify() { self.location = UUID() } private final class Storage: @unchecked Sendable { fileprivate var id: ID init(id: ID = .location(UUID())) { self.id = id } enum ID: Equatable, Hashable, Sendable { case location(UUID) indirect case tag(Int, ID) var location: UUID { get { switch self { case let .location(location): return location case let .tag(_, id): return id.location } } set { switch self { case .location: self = .location(newValue) case .tag(let tag, var id): id.location = newValue self = .tag(tag, id) } } } } } } @inlinable public func _$isIdentityEqual<T: ObservableState>( _ lhs: T, _ rhs: T ) -> Bool { lhs._$id == rhs._$id } @inlinable public func _$isIdentityEqual<ID: Hashable, T: ObservableState>( _ lhs: IdentifiedArray<ID, T>, _ rhs: IdentifiedArray<ID, T> ) -> Bool { areOrderedSetsDuplicates(lhs.ids, rhs.ids) } @inlinable public func _$isIdentityEqual<C: Collection>( _ lhs: C, _ rhs: C ) -> Bool where C.Element: ObservableState { lhs.count == rhs.count && zip(lhs, rhs).allSatisfy { $0._$id == $1._$id } } // NB: This is a fast path so that String is not checked as a collection. @inlinable public func _$isIdentityEqual(_ lhs: String, _ rhs: String) -> Bool { false } @inlinable public func _$isIdentityEqual<T>(_ lhs: T, _ rhs: T) -> Bool { guard !_isPOD(T.self) else { return false } func openCollection<C: Collection>(_ lhs: C, _ rhs: Any) -> Bool { guard C.Element.self is ObservableState.Type else { return false } func openIdentifiable<Element: Identifiable>(_: Element.Type) -> Bool? { guard let lhs = lhs as? IdentifiedArrayOf<Element>, let rhs = rhs as? IdentifiedArrayOf<Element> else { return nil } return areOrderedSetsDuplicates(lhs.ids, rhs.ids) } if let identifiable = C.Element.self as? any Identifiable.Type, let result = openIdentifiable(identifiable) { return result } else if let rhs = rhs as? C { return lhs.count == rhs.count && zip(lhs, rhs).allSatisfy(_$isIdentityEqual) } else { return false } } if let lhs = lhs as? any ObservableState, let rhs = rhs as? any ObservableState { return lhs._$id == rhs._$id } else if let lhs = lhs as? any Collection { return openCollection(lhs, rhs) } else { return false } } @inlinable public func _$willModify<T>(_: inout T) {} @inlinable public func _$willModify<T: ObservableState>(_ value: inout T) { value._$willModify() } #endif
yonaskolb/SwiftComponent
16
Where architecture meets tooling
Swift
yonaskolb
Yonas Kolb
Sources/SwiftComponent/Observation/ObservationStateRegistrar.swift
Swift
// Copyright (c) 2024 Point-Free, Inc. // https://github.com/pointfreeco/swift-composable-architecture/blob/main/LICENSE #if canImport(Perception) /// Provides storage for tracking and access to data changes. public struct ObservationStateRegistrar: Sendable { public private(set) var id = ObservableStateID() @usableFromInline let registrar = PerceptionRegistrar() public init() {} public mutating func _$willModify() { self.id._$willModify() } } extension ObservationStateRegistrar: Equatable, Hashable, Codable { public static func == (_: Self, _: Self) -> Bool { true } public func hash(into hasher: inout Hasher) {} public init(from decoder: Decoder) throws { self.init() } public func encode(to encoder: Encoder) throws {} } #if canImport(Observation) @available(iOS 17, macOS 14, tvOS 17, watchOS 10, *) extension ObservationStateRegistrar { /// Registers access to a specific property for observation. /// /// - Parameters: /// - subject: An instance of an observable type. /// - keyPath: The key path of an observed property. @inlinable public func access<Subject: Observable, Member>( _ subject: Subject, keyPath: KeyPath<Subject, Member> ) { self.registrar.access(subject, keyPath: keyPath) } /// Mutates a value to a new value, and decided to notify observers based on the identity of /// the value. /// /// - Parameters: /// - subject: An instance of an observable type. /// - keyPath: The key path of an observed property. /// - value: The value being mutated. /// - newValue: The new value to mutate with. /// - isIdentityEqual: A comparison function that determines whether two values have the /// same identity or not. @inlinable public func mutate<Subject: Observable, Member, Value>( _ subject: Subject, keyPath: KeyPath<Subject, Member>, _ value: inout Value, _ newValue: Value, _ isIdentityEqual: (Value, Value) -> Bool ) { if isIdentityEqual(value, newValue) { value = newValue } else { self.registrar.withMutation(of: subject, keyPath: keyPath) { value = newValue } } } /// A no-op for non-observable values. /// /// See ``willModify(_:keyPath:_:)-3ybfo`` for info on what this method does when used with /// observable values. @inlinable public func willModify<Subject: Observable, Member>( _ subject: Subject, keyPath: KeyPath<Subject, Member>, _ member: inout Member ) -> Member { member } /// A property observation called before setting the value of the subject. /// /// - Parameters: /// - subject: An instance of an observable type.` /// - keyPath: The key path of an observed property. /// - member: The value in the subject that will be set. @inlinable public func willModify<Subject: Observable, Member: ObservableState>( _ subject: Subject, keyPath: KeyPath<Subject, Member>, _ member: inout Member ) -> Member { member._$willModify() return member } /// A property observation called after setting the value of the subject. /// /// If the identity of the value changed between ``willModify(_:keyPath:_:)-3ybfo`` and /// ``didModify(_:keyPath:_:_:_:)-q3nd``, observers are notified. @inlinable public func didModify<Subject: Observable, Member>( _ subject: Subject, keyPath: KeyPath<Subject, Member>, _ member: inout Member, _ oldValue: Member, _ isIdentityEqual: (Member, Member) -> Bool ) { if !isIdentityEqual(oldValue, member) { let newValue = member member = oldValue self.mutate(subject, keyPath: keyPath, &member, newValue, isIdentityEqual) } } } #endif extension ObservationStateRegistrar { @_disfavoredOverload @inlinable public func access<Subject: Perceptible, Member>( _ subject: Subject, keyPath: KeyPath<Subject, Member> ) { self.registrar.access(subject, keyPath: keyPath) } @_disfavoredOverload @inlinable public func mutate<Subject: Perceptible, Member, Value>( _ subject: Subject, keyPath: KeyPath<Subject, Member>, _ value: inout Value, _ newValue: Value, _ isIdentityEqual: (Value, Value) -> Bool ) { if isIdentityEqual(value, newValue) { value = newValue } else { self.registrar.withMutation(of: subject, keyPath: keyPath) { value = newValue } } } @_disfavoredOverload @inlinable public func willModify<Subject: Perceptible, Member>( _ subject: Subject, keyPath: KeyPath<Subject, Member>, _ member: inout Member ) -> Member { return member } @_disfavoredOverload @inlinable public func willModify<Subject: Perceptible, Member: ObservableState>( _ subject: Subject, keyPath: KeyPath<Subject, Member>, _ member: inout Member ) -> Member { member._$willModify() return member } @_disfavoredOverload @inlinable public func didModify<Subject: Perceptible, Member>( _ subject: Subject, keyPath: KeyPath<Subject, Member>, _ member: inout Member, _ oldValue: Member, _ isIdentityEqual: (Member, Member) -> Bool ) { if !isIdentityEqual(oldValue, member) { let newValue = member member = oldValue self.mutate(subject, keyPath: keyPath, &member, newValue, isIdentityEqual) } } } #endif
yonaskolb/SwiftComponent
16
Where architecture meets tooling
Swift
yonaskolb
Yonas Kolb
Sources/SwiftComponent/Path.swift
Swift
import Foundation public struct ComponentPath: CustomStringConvertible, Equatable, Hashable { public static func == (lhs: ComponentPath, rhs: ComponentPath) -> Bool { lhs.string == rhs.string } public let path: [any ComponentModel.Type] var pathString: String { path.map { $0.baseName }.joined(separator: "/") } public var string: String { return pathString } public var description: String { string } init(_ component: any ComponentModel.Type) { self.path = [component] } init(_ path: [any ComponentModel.Type]) { self.path = path } func contains(_ path: ComponentPath) -> Bool { self.pathString.hasPrefix(path.pathString) } func appending(_ component: any ComponentModel.Type) -> ComponentPath { ComponentPath(path + [component]) } var parent: ComponentPath? { if path.count > 1 { return ComponentPath(path.dropLast()) } else { return nil } } func relative(to component: ComponentPath) -> ComponentPath { guard contains(component) else { return self } return ComponentPath(Array(path.dropFirst(component.path.count))) } var droppingRoot: ComponentPath? { if !path.isEmpty { return ComponentPath(Array(path.dropFirst())) } else { return nil } } public func hash(into hasher: inout Hasher) { hasher.combine(pathString) } }
yonaskolb/SwiftComponent
16
Where architecture meets tooling
Swift
yonaskolb
Yonas Kolb
Sources/SwiftComponent/Presentation.swift
Swift
import Foundation import SwiftUI //TODO: turn into protocol that handles any sort of presentation based on view modifiers public enum Presentation { case sheet case push case fullScreenCover @available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *) // use NavigationView instead of NavigationStack for push presentations on iOS 16. public static var useNavigationViewOniOS16 = false } // wip //public protocol PresentationType<Destination> { // // associatedtype PresentationView: View // associatedtype Destination // associatedtype DestinationView: View // func attach<V: View>(_ view: V, destination: Binding<Destination?>, destinationView: (Destination) -> DestinationView) -> Self.PresentationView //} // //public struct SheetPresentation<D, DV: View>: PresentationType { // public typealias Destination = D // public typealias DestinationView = DV // var destination: Binding<Destination?> // var destinationView: (Destination) -> DV // // public func attach<V: View>(_ view: V, destination: Binding<Destination?>, destinationView: (Destination) -> DestinationView) -> some View { // view.sheet(isPresented: Binding(get: { destination.wrappedValue != nil}, set: { if !$0 { destination.wrappedValue = nil }})) { // if let destination = destination.wrappedValue { // destinationView(destination) // } // } // } //}
yonaskolb/SwiftComponent
16
Where architecture meets tooling
Swift
yonaskolb
Yonas Kolb
Sources/SwiftComponent/ResourceState.swift
Swift
import Foundation import SwiftUI import Perception @propertyWrapper public struct ResourceState<Value> { public var wrappedValue: Value? { get { content } set { content = newValue } } public var content: Value? public var error: Error? public var isLoading: Bool = false public init(wrappedValue: Value?) { self.wrappedValue = wrappedValue } public init(content: Value? = nil, error: Error? = nil, isLoading: Bool = false) { self.content = content self.error = error self.isLoading = isLoading } public enum State { case unloaded case loading case loaded(Value) case error(Error) public enum ResourceStateType { case loading case content case error } } /// order is the order that state type will be returned if it's not nil. States that are left out will be returned in the order content, loading, error public func state(order: [State.ResourceStateType] = [.content, .loading, .error]) -> State { for state in order { switch state { case .content: if let content { return .loaded(content) } case .error: if let error { return .error(error) } case .loading: if isLoading { return .loading } } } // in case order is empty or doesn't contain all cases if let content { return .loaded(content) } else if isLoading { return .loading } else if let error { return .error(error) } else { return .unloaded } } public var projectedValue: ResourceState { get { return self } set { self = newValue } } } public extension ResourceState { static var unloaded: ResourceState { ResourceState(content: nil, error: nil, isLoading: false) } static var loading: ResourceState { ResourceState(content: nil, error: nil, isLoading: true) } static func content<C>(_ content: C) -> ResourceState<C> { ResourceState<C>(content: content, error: nil, isLoading: false) } static func error(_ error: Error) -> ResourceState { ResourceState(content: nil, error: error, isLoading: false) } } extension ResourceState: Equatable where Value: Equatable { public static func == (lhs: ResourceState<Value>, rhs: ResourceState<Value>) -> Bool { lhs.content == rhs.content && lhs.isLoading == rhs.isLoading && lhs.error?.localizedDescription == rhs.error?.localizedDescription } } extension ResourceState: Hashable where Value: Hashable { public func hash(into hasher: inout Hasher) { hasher.combine(content) hasher.combine(isLoading) hasher.combine(error?.localizedDescription) } } extension ResourceState where Value: Collection, Value: ExpressibleByArrayLiteral { public var list: Value { get { if let content { return content } else { return [] } } set { content = newValue } } public static var empty: ResourceState { self.content([]) } } extension ResourceState { public func map<T>(_ map: (Value) -> T) -> ResourceState<T> { ResourceState<T>(content: content.map(map), error: error, isLoading: isLoading) } } func getResourceTaskName<State, R>(_ keyPath: KeyPath<State, ResourceState<R>>) -> String { "load \(keyPath.propertyName ?? "resource")" } extension ComponentModel { @MainActor public func loadResource<S>(_ keyPath: WritableKeyPath<State, ResourceState<S>>, animation: Animation? = nil, overwriteContent: Bool = true, file: StaticString = #filePath, line: UInt = #line, load: @MainActor @escaping () async throws -> S) async { mutate(keyPath.appending(path: \.isLoading), true, animation: animation) let name = getResourceTaskName(keyPath) await store.task(name, cancellable: true, source: .capture(file: file, line: line)) { @MainActor in let content = try await load() self.mutate(keyPath.appending(path: \.content), content, animation: animation) if self.store.state[keyPath: keyPath.appending(path: \.error)] != nil { self.mutate(keyPath.appending(path: \.error), nil, animation: animation) } return content } catch: { error in if overwriteContent, store.state[keyPath: keyPath.appending(path: \.content)] != nil { mutate(keyPath.appending(path: \.content), nil, animation: animation) } mutate(keyPath.appending(path: \.error), error, animation: animation) } mutate(keyPath.appending(path: \.isLoading), false, animation: animation) } } /// A simple view for visualizing a Resource. If you want custom UI for loading and unloaded states, use a custom view and switch over Resource.state or access it's other properties directly public struct ResourceView<Value: Equatable, Content: View, ErrorView: View, LoadingView: View>: View { // the order of states if they are not nil. States that are left out will be returned in the order content, loading, error let stateOrder: [ResourceState<Value>.State.ResourceStateType] let resource: ResourceState<Value> let content: (Value) -> Content let loading: () -> LoadingView let error: (Error) -> ErrorView public init(_ resource: ResourceState<Value>, stateOrder: [ResourceState<Value>.State.ResourceStateType] = [.content, .loading, .error], @ViewBuilder loading:@escaping () -> LoadingView, @ViewBuilder content: @escaping (Value) -> Content, @ViewBuilder error: @escaping (Error) -> ErrorView) { self.resource = resource self.stateOrder = stateOrder self.loading = loading self.content = content self.error = error } public init(_ resource: ResourceState<Value>, stateOrder: [ResourceState<Value>.State.ResourceStateType] = [.content, .loading, .error], @ViewBuilder content: @escaping (Value) -> Content, @ViewBuilder error: @escaping (Error) -> ErrorView) where LoadingView == ResourceLoadingView { self.init( resource, stateOrder: stateOrder, loading: { ResourceLoadingView() }, content: content, error: error ) } public var body: some View { VStack { switch resource.state(order: stateOrder) { case .loaded(let value): content(value) case .error(let error): self.error(error) case .loading: loading() case .unloaded: Spacer() } } } } public struct ResourceLoadingView: View { public var body: some View { Spacer() ProgressView() Spacer() } }
yonaskolb/SwiftComponent
16
Where architecture meets tooling
Swift
yonaskolb
Yonas Kolb
Sources/SwiftComponent/Routing.swift
Swift
import Foundation extension ComponentModel { @MainActor @discardableResult public func route<Child: ComponentModel>(to route: (ComponentRoute<Child>) -> Route, state: Child.State, childRoute: Child.Route? = nil, file: StaticString = #filePath, line: UInt = #line) -> ComponentRoute<Child> { let componentRoute = ComponentRoute<Child>(state: state, route: childRoute) store.present(route(componentRoute), source: .capture(file: file, line: line)) return componentRoute } } extension ComponentModel { // MARK: different environment public func connect<Child>(_ route: ComponentRoute<Child>, environment: Child.Environment, output toInput: @escaping (Child.Output) -> Input) -> RouteConnection { route.setStore(store.scope(state: .value(route.state), environment: environment, route: route.route, output: .input(toInput))) return RouteConnection() } public func connect<Child>(_ route: ComponentRoute<Child>, environment: Child.Environment, output toOutput: @escaping (Child.Output) -> Output) -> RouteConnection { route.setStore(store.scope(state: .value(route.state), environment: environment, route: route.route, output: .output(toOutput))) return RouteConnection() } public func connect<Child>(_ route: ComponentRoute<Child>, environment: Child.Environment) -> RouteConnection where Child.Output == Never { route.setStore(store.scope(state: .value(route.state), environment: environment, route: route.route)) return RouteConnection() } public func connect<Child: ComponentModel>(_ route: ComponentRoute<Child>, scope: Scope<Child>, environment: Child.Environment) -> RouteConnection { let routeViewModel = scope.convert(store.viewModel()) route.setStore(routeViewModel.store) return RouteConnection() } // MARK: same environment public func connect<Child>(_ route: ComponentRoute<Child>, output toInput: @escaping (Child.Output) -> Input) -> RouteConnection where Environment == Child.Environment { route.setStore(store.scope(state: .value(route.state), route: route.route, output: .input(toInput))) return RouteConnection() } public func connect<Child>(_ route: ComponentRoute<Child>, output toOutput: @escaping (Child.Output) -> Output) -> RouteConnection where Environment == Child.Environment { route.setStore(store.scope(state: .value(route.state), route: route.route, output: .output(toOutput))) return RouteConnection() } public func connect<Child>(_ route: ComponentRoute<Child>) -> RouteConnection where Child.Output == Never, Environment == Child.Environment { route.setStore(store.scope(state: .value(route.state), route: route.route)) return RouteConnection() } public func connect<Child: ComponentModel>(_ route: ComponentRoute<Child>, scope: Scope<Child>) -> RouteConnection where Environment == Child.Environment { let routeViewModel = scope.convert(store.viewModel()) route.setStore(routeViewModel.store) return RouteConnection() } } public struct RouteConnection { internal init() { } } @MainActor public class ComponentRoute<Model: ComponentModel> { let state: Model.State var route: Model.Route? var dependencies: ComponentDependencies var store: ComponentStore<Model>? public var model: ViewModel<Model> { guard let store else { fatalError("store was not connected" )} return ViewModel(store: store) } public init(state: Model.State, route: Model.Route? = nil) { self.state = state self.route = route self.dependencies = .init() } func setStore(_ store: ComponentStore<Model>) { self.store = store store.dependencies.apply(dependencies) } } extension ComponentRoute where Model.Route == Never { convenience init(state: Model.State) { self.init(state: state, route: nil) } } @resultBuilder public struct RouteBuilder { public static func buildBlock<Route>() -> [ComponentModelRoute<Route>] { [] } public static func buildBlock<Route>(_ routes: ComponentModelRoute<Route>...) -> [ComponentModelRoute<Route>] { routes } public static func buildBlock<Route>(_ routes: [ComponentModelRoute<Route>]) -> [ComponentModelRoute<Route>] { routes } } public struct ComponentModelRoute<Route> { public let name: String public let route: Route public init(_ name: String, _ route: Route) { self.name = name self.route = route } }
yonaskolb/SwiftComponent
16
Where architecture meets tooling
Swift
yonaskolb
Yonas Kolb
Sources/SwiftComponent/Snapshotting.swift
Swift
import Foundation import SwiftUI public struct SnapshotModifier { var apply: (AnyView) -> AnyView public static func environment<V>(_ keyPath: WritableKeyPath<EnvironmentValues, V>, _ value: V) -> Self { SnapshotModifier { AnyView($0.environment(keyPath, value)) } } func render(_ view: some View) -> AnyView { apply(AnyView(view)) } } extension Component { /// Returns all snapshots, both static and those made within tests by running those tests @MainActor public static func allSnapshots() async -> [ComponentSnapshot<Model>] { var allSnapshots = self.snapshots for test in tests { // only run tests if they contain snapshots steps, otherwise we can skip for performance let testContainsSnapshots = test.steps.contains { !$0.snapshots.isEmpty } if testContainsSnapshots { let testSnapshots = await run(test, assertions: [], onlyCollectSnapshots: true).snapshots allSnapshots.append(contentsOf: testSnapshots) } } return allSnapshots } /// must be called from a test target with an app host @MainActor public static func generateSnapshots( size: CGSize, files: Set<SnapshotFile> = [.image], snapshotDirectory: URL? = nil, variants: [String: [SnapshotModifier]] = [:], file: StaticString = #file ) async throws -> Set<URL> { let snapshots = await allSnapshots() var snapshotPaths: Set<URL> = [] for snapshot in snapshots { let filePaths = try await write( snapshot: snapshot, size: size, files: files, snapshotDirectory: snapshotDirectory, variants: variants, file: file ) snapshotPaths = snapshotPaths.union(filePaths) } return snapshotPaths } @MainActor public static func write( snapshot: ComponentSnapshot<Model>, size: CGSize, files: Set<SnapshotFile> = [.image], snapshotDirectory: URL? = nil, variants: [String: [SnapshotModifier]] = [:], file: StaticString = #file ) async throws -> [URL] { try await write( view: view(snapshot: snapshot).previewReference(), state: snapshot.state, name: "\(name).\(snapshot.name)", size: size, files: files, snapshotDirectory: snapshotDirectory, variants: variants, file: file ) } @MainActor static func write<V: View>( view: V, state: Model.State, name: String, size: CGSize, files: Set<SnapshotFile> = [.image], snapshotDirectory: URL? = nil, variants: [String: [SnapshotModifier]], file: StaticString = #file ) async throws -> [URL] { var writtenFiles: [URL] = [] let fileUrl = URL(fileURLWithPath: "\(file)", isDirectory: false) let snapshotsPath = snapshotDirectory ?? fileUrl .deletingLastPathComponent() .appendingPathComponent("Snapshots") try FileManager.default.createDirectory(at: snapshotsPath, withIntermediateDirectories: true) let filePath = snapshotsPath.appendingPathComponent(name) #if canImport(UIKit) // accessibility markdown if files.contains(.accessibilty) { let accessibilityFilePath = filePath.appendingPathExtension("md") let accessibilitySnapshot = view.accessibilityHierarchy().markdown() try accessibilitySnapshot.data(using: .utf8)?.write(to: accessibilityFilePath) writtenFiles.append(accessibilityFilePath) } // image if files.contains(.image) { if variants.isEmpty { let imageFilePath = filePath.appendingPathExtension("png") let imageSnapshot = view.snapshot(size: size) try imageSnapshot.pngData()?.write(to: imageFilePath) writtenFiles.append(imageFilePath) } else { for (variant, environments) in variants { var modifiedView = AnyView(view) for environment in environments { modifiedView = environment.render(modifiedView) } let imageSnapshot = modifiedView.snapshot(size: size) let imageFilePath = snapshotsPath.appendingPathComponent("\(name).\(variant)").appendingPathExtension("png") try imageSnapshot.pngData()?.write(to: imageFilePath) writtenFiles.append(imageFilePath) } } } #endif // state if files.contains(.state) { let stateFilePath = filePath.appendingPathExtension("swift") let stateString = dumpToString(state) try stateString.data(using: .utf8)?.write(to: stateFilePath) writtenFiles.append(stateFilePath) } return writtenFiles } } public enum SnapshotFile { case image case accessibilty case state } #if os(iOS) extension View { @MainActor func snapshot(size: CGSize) -> UIImage { let rootView = self .edgesIgnoringSafeArea(.top) let renderer = UIGraphicsImageRenderer(size: size) return rootView.renderView(in: .init(origin: .zero, size: size)) { view in renderer.image { _ in view.drawHierarchy(in: view.bounds, afterScreenUpdates: true) } } } } #endif
yonaskolb/SwiftComponent
16
Where architecture meets tooling
Swift
yonaskolb
Yonas Kolb
Sources/SwiftComponent/Testing/Snapshot.swift
Swift
import Foundation public struct ComponentSnapshot<Model: ComponentModel> { public var name: String public var state: Model.State public var environment: Model.Environment public var route: Model.Route? public var tags: Set<String> public var source: Source public var dependencies: ComponentDependencies = .init() } extension ComponentSnapshot { public init( _ name: String = "snapshot", state: Model.State, environment: Model.Environment? = nil, route: Model.Route? = nil, tags: Set<String> = [], file: StaticString = #file, line: UInt = #line ) { self.init( name: name, state: state, environment: (environment ?? Model.Environment.preview).copy(), route: route, tags: tags, source: .capture(file: file, line: line) ) } } struct TestSnapshot { let name: String let tags: Set<String> } extension TestStep { public static func snapshot(_ name: String, environment: Model.Environment? = nil, tags: Set<String> = [], file: StaticString = #file, line: UInt = #line) -> Self { var step = Self(title: "Snapshot", details: name, file: file, line: line) { context in let snapshot = ComponentSnapshot<Model>( name: name, state: context.state, environment: (environment ?? context.model.environment).copy(), route: context.model.route, tags: tags, source: .capture(file: file, line: line) ) snapshot.dependencies.apply(context.model.dependencies) context.snapshots.append(snapshot) } step.snapshots = [TestSnapshot(name: name, tags: tags)] return step } } extension ComponentSnapshot { @MainActor public func viewModel() -> ViewModel<Model> { ViewModel(state: state, environment: environment, route: route).apply(dependencies) } } extension Component { static var testSnapshots: [TestSnapshot] { tests.reduce([]) { $0 + $1.steps.flatMap(\.snapshots) } } } @resultBuilder public struct SnapshotBuilder<Model: ComponentModel> { public static func buildBlock() -> [ComponentSnapshot<Model>] { [] } public static func buildExpression(_ expression: ComponentSnapshot<Model>) -> [ComponentSnapshot<Model>] { [expression] } public static func buildExpression(_ expression: [ComponentSnapshot<Model>]) -> [ComponentSnapshot<Model>] { expression } public static func buildPartialBlock(first: [ComponentSnapshot<Model>]) -> [ComponentSnapshot<Model>] { first } public static func buildPartialBlock(accumulated: [ComponentSnapshot<Model>], next: [ComponentSnapshot<Model>]) -> [ComponentSnapshot<Model>] { accumulated + next } }
yonaskolb/SwiftComponent
16
Where architecture meets tooling
Swift
yonaskolb
Yonas Kolb
Sources/SwiftComponent/Testing/Test.swift
Swift
import Foundation public struct Test<ComponentType: Component>: Identifiable { public typealias Model = ComponentType.Model public init(_ name: String? = nil, assertions: [TestAssertion]? = nil, environment: Model.Environment? = nil, file: StaticString = #filePath, line: UInt = #line, @TestStepBuilder<Model> _ steps: () -> [TestStep<Model>]) where Model.State == Void { self.init(name, state: (), assertions: assertions, environment: environment ?? ComponentType.preview.environment.copy(), file: file, line: line, steps) } public init(_ name: String? = nil, state: Model.State, assertions: [TestAssertion]? = nil, environment: Model.Environment? = nil, file: StaticString = #filePath, line: UInt = #line, @TestStepBuilder<Model> _ steps: () -> [TestStep<Model>]) { self.init(name, state: state, assertions: assertions, environment: environment ?? ComponentType.preview.environment.copy(), file: file, line: line, steps) } public init(_ name: String? = nil, assertions: [TestAssertion]? = nil, environment: Model.Environment? = nil, file: StaticString = #filePath, line: UInt = #line, @TestStepBuilder<Model> _ steps: () -> [TestStep<Model>]) { self.init(name, state: ComponentType.preview.state, assertions: assertions, environment: environment ?? ComponentType.preview.environment.copy(), file: file, line: line, steps) } public init(_ name: String? = nil, state: Model.State, assertions: [TestAssertion]? = nil, environment: Model.Environment, file: StaticString = #filePath, line: UInt = #line, @TestStepBuilder<Model> _ steps: () -> [TestStep<Model>]) { self.name = name self.state = state self.environment = environment self.assertions = assertions self.source = .capture(file: file, line: line) self.steps = steps() self.dependencies = ComponentDependencies() } public var name: String? public var index: Int = 0 public var testName: String { name ?? (index == 0 ? "Test" : "Test \(index + 1)") } public var id: String { testName } public var state: Model.State public var environment: Model.Environment public var steps: [TestStep<Model>] public let source: Source public let assertions: [TestAssertion]? public var dependencies: ComponentDependencies } @resultBuilder public struct TestBuilder<ComponentType: Component> { public static func buildBlock() -> [Test<ComponentType>] { [] } public static func buildBlock(_ tests: Test<ComponentType>...) -> [Test<ComponentType>] { addIndexes(tests) } public static func buildBlock(_ tests: [Test<ComponentType>]) -> [Test<ComponentType>] { addIndexes(tests) } public static func buildExpression(_ test: Test<ComponentType>) -> Test<ComponentType> { test } static func addIndexes(_ tests: [Test<ComponentType>]) -> [Test<ComponentType>] { tests.enumerated().map { index, test in var test = test test.index = index return test } } }
yonaskolb/SwiftComponent
16
Where architecture meets tooling
Swift
yonaskolb
Yonas Kolb
Sources/SwiftComponent/Testing/TestAssertion.swift
Swift
import Foundation import Runtime extension [TestAssertion] { public static var none: Self { [] } public static var all: Self { [ OutputTestAssertion(), TaskTestAssertion(), RouteTestAssertion(), EmptyRouteTestAssertion(), StateTestAssertion(), DependencyTestAssertion(), ] } public static var standard: Self { [ OutputTestAssertion(), TaskTestAssertion(), RouteTestAssertion(), EmptyRouteTestAssertion(), ] } } public protocol TestAssertion { var id: String { get } @MainActor func assert<Model: ComponentModel>(context: inout TestAssertionContext<Model>) } public extension TestAssertion { var id: String { String(describing: Self.self)} } public struct TestAssertionContext<Model: ComponentModel> { public let events: [Event] public let source: Source public var testContext: TestContext<Model> public var errors: [TestError] = [] public var stepID: UUID } // snippet replacement for copy and pasting: "<#State# >" without space /// asserts all outputs have been expected struct OutputTestAssertion: TestAssertion { func assert<Model: ComponentModel>(context: inout TestAssertionContext<Model>) { for event in context.events { switch event.type { case .output(let output): let enumCase = getEnumCase(output) context.errors.append(TestError(error: "Unexpected output \(enumCase.name.quoted)", source: context.source, fixit: ".expectOutput(.\(enumCase.name)\(enumCase.values.isEmpty ? "" : "(<#output#>)"))")) default: break } } } } /// asserts all tasks have been expected struct TaskTestAssertion: TestAssertion { func assert<Model: ComponentModel>(context: inout TestAssertionContext<Model>) { for event in context.events { switch event.type { case .task(let result): let taskID = (try? typeInfo(of: Model.Task.self).kind) == .enum ? ".\(result.name)" : result.name.quoted let fixit = ".expectTask(\(taskID)\(result.successful ? "" : ", successful: false"))" context.errors.append(TestError(error: "Unexpected task \(result.name.quoted)", source: context.source, fixit: fixit)) default: break } } } } /// asserts all routes have been expected struct RouteTestAssertion: TestAssertion { func assert<Model: ComponentModel>(context: inout TestAssertionContext<Model>) { for event in context.events { switch event.type { case .route(let route): context.errors.append(TestError(error: "Unexpected route \(getEnumCase(route).name.quoted)", source: context.source, fixit: ".expectRoute(/Model.Route.\(getEnumCase(route).name), state: <#State#>)")) default: break } } } } /// asserts all routes have been expected struct EmptyRouteTestAssertion: TestAssertion { func assert<Model: ComponentModel>(context: inout TestAssertionContext<Model>) { for event in context.events { switch event.type { case .dismissRoute: context.errors.append(TestError(error: "Unexpected empty route", source: context.source, fixit: ".expectEmptyRoute()")) default: break } } } } /// asserts all state mutations have been expected struct StateTestAssertion: TestAssertion { func assert<Model: ComponentModel>(context: inout TestAssertionContext<Model>) { if let diff = StateDump.diff(context.testContext.state, context.testContext.model.state) { context.errors.append(.init(error: "Unexpected state", diff: diff, source: context.source, fixit: ".expectState(\\.<#keypath#>, <#state#>)")) } } } /// asserts all used dependency have been expected struct DependencyTestAssertion: TestAssertion { func assert<Model: ComponentModel>(context: inout TestAssertionContext<Model>) { var setDependencies = context.testContext.model.dependencies.setDependencies // make sure if a dependency path is accessed but the whole dependency is overriden that counts as being set setDependencies.formUnion(Set(setDependencies.map { $0.components(separatedBy: ".").first! })) let unsetDependencies = context.testContext.testCoverage.dependencies.subtracting(setDependencies) if !unsetDependencies.isEmpty { context.testContext.testCoverage.dependencies.subtract(unsetDependencies) let dependencies = unsetDependencies.sorted() for dependency in dependencies { // TODO: add a fixit, but first allow a fixit to insert BEFORE the source line with a Position enum context.errors.append(.init(error: "Uncontrolled use of dependency \(dependency.quoted)", source: context.source)) } } } }
yonaskolb/SwiftComponent
16
Where architecture meets tooling
Swift
yonaskolb
Yonas Kolb
Sources/SwiftComponent/Testing/TestExpectation.swift
Swift
import Foundation public struct TestExpectation<Model: ComponentModel> { public let title: String public let details: String? public let source: Source @MainActor let run: (inout Context) -> Void public var description: String { var string = title if let details { string += " \(details)" } return string } public struct Context { var testContext: TestContext<Model> let source: Source var events: [Event] var errors: [TestError] = [] public var model: ViewModel<Model> { testContext.model } public mutating func findEventValue<T>(_ find: (Event) -> T?) -> T? { for (index, event) in events.enumerated() { if let eventValue = find(event) { events.remove(at: index) return eventValue } } return nil } public mutating func error(_ error: String, diff: [String]? = nil) { errors.append(TestError(error: error, diff: diff, source: source)) } } } extension TestStep { public func addExpectation(title: String, details: String? = nil, file: StaticString, line: UInt, run: @MainActor @escaping (inout TestExpectation<Model>.Context) -> Void) -> Self { var step = self let expectation = TestExpectation<Model>(title: title, details: details, source: .capture(file: file, line: line), run: run) step.expectations.append(expectation) return step } }
yonaskolb/SwiftComponent
16
Where architecture meets tooling
Swift
yonaskolb
Yonas Kolb
Sources/SwiftComponent/Testing/TestExpectations.swift
Swift
import Foundation extension TestStep { public func expectOutput(_ output: Model.Output, file: StaticString = #filePath, line: UInt = #line) -> Self { addExpectation(title: "Expect Output", details: getEnumCase(output).name, file: file, line: line) { context in let foundOutput: Model.Output? = context.findEventValue { event in if case .output(let output) = event.type, let output = output as? Model.Output { return output } return nil } if let foundOutput { if let difference = StateDump.diff(foundOutput, output) { context.error("Unexpected output value \(getEnumCase(foundOutput).name.quoted)", diff: difference) } } else { context.error("Output \(getEnumCase(output).name.quoted) was not sent") } } } private func expectTask(name: String, successful: Bool?, ongoing: Bool? = nil, file: StaticString = #filePath, line: UInt = #line) -> Self { let result: String switch successful { case .none: result = "" case false: result = "failure" case true: result = " success" default: result = "" } return addExpectation(title: "Expect Task", details: "\(name.quoted)\(result)", file: file, line: line) { context in let result: TaskResult? = context.findEventValue { event in if case .task(let taskResult) = event.type, taskResult.name == name { return taskResult } return nil } if let result { switch result.result { case .failure: if successful == true { context.error("Expected \(name.quoted) task to succeed, but it failed") } case .success: if successful == false { context.error("Expected \(name.quoted) task to fail, but it succeeded") } } } else { context.error("Task \(name.quoted) was not sent") } if let ongoing { if ongoing, context.model.store.tasksByID[name] == nil { context.error("Expected \(name.quoted) to still be running") } else if !ongoing, context.model.store.tasksByID[name] != nil { context.error("Expected \(name.quoted) not to still be running") } } } } public func expectTask(_ taskID: Model.Task, successful: Bool? = nil, ongoing: Bool? = nil, file: StaticString = #filePath, line: UInt = #line) -> Self { expectTask(name: taskID.taskName, successful: successful, ongoing: ongoing, file: file, line: line) } public func expectTask(_ taskID: String, successful: Bool? = nil, ongoing: Bool? = nil, file: StaticString = #filePath, line: UInt = #line) -> Self { expectTask(name: taskID, successful: successful, ongoing: ongoing, file: file, line: line) } public func expectCancelledTask(_ taskID: String, file: StaticString = #filePath, line: UInt = #line) -> Self { addExpectation(title: "Expect task is not running", details: taskID.quoted, file: file, line: line) { context in if context.model.store.tasksByID[taskID] != nil { context.error("Task \(taskID.quoted) is unexpectedly running") } else if !context.model.store.cancelledTasks.contains(taskID) { context.error("Task \(taskID.quoted) was not cancelled") } } } public func expectCancelledTask(_ taskID: Model.Task, file: StaticString = #filePath, line: UInt = #line) -> Self { expectCancelledTask(taskID.taskName, file: file, line: line) } public func expectDependency<Value>(_ keyPath: KeyPath<DependencyValues, Value>, file: StaticString = #filePath, line: UInt = #line) -> Self { addExpectation(title: "Expect dependency", details: keyPath.propertyName, file: file, line: line) { context in if let name = keyPath.propertyName { if !context.model.dependencies.accessedDependencies.contains(name) { context.error("Expected accessed dependency \(name)") context.model.dependencies.accessedDependencies.remove(name) } } } } //TODO: also clear mutation assertions public func expectResourceTask<R>(_ keyPath: KeyPath<Model.State, ResourceState<R>>, successful: Bool? = nil, file: StaticString = #filePath, line: UInt = #line) -> Self { expectTask(name: getResourceTaskName(keyPath), successful: successful, file: file, line: line) .expectState(keyPath.appending(path: \.isLoading), false, file: file, line: line) } public func expectEmptyRoute(file: StaticString = #filePath, line: UInt = #line) -> Self { addExpectation(title: "Expect empty route", file: file, line: line) { context in context.findEventValue { event in if case .dismissRoute = event.type { return () } return nil } if let route = context.model.route { context.error("Unexpected Route \(getEnumCase(route).name.quoted)") } } } public func expectRoute<Child: ComponentModel>(_ path: AnyCasePath<Model.Route, ComponentRoute<Child>>, state expectedState: Child.State, childRoute: Child.Route? = nil, file: StaticString = #filePath, line: UInt = #line) -> Self { addExpectation(title: "Expect route", details: Child.baseName, file: file, line: line) { context in let foundRoute: Model.Route? = context.findEventValue { event in if case .route(let route) = event.type, let route = route as? Model.Route { return route } return nil } if let route = foundRoute { if let foundComponentRoute = path.extract(from: route) { if let difference = StateDump.diff(expectedState, foundComponentRoute.state) { context.error("Unexpected state in route \(getEnumCase(route).name.quoted)", diff: difference) } // TODO: compare nested route } else { context.error("Unexpected route \(getEnumCase(route).name.quoted)") } } else { context.error("Unexpected empty route") } } } public func validateDependency<T>(_ error: String, _ keyPath: KeyPath<DependencyValues, T>, _ validateDependency: @escaping (T) -> Bool, file: StaticString = #filePath, line: UInt = #line) -> Self { addExpectation(title: "Validate dependency", details: String(describing: T.self).quoted, file: file, line: line) { context in let dependency = context.model.dependencies[dynamicMember: keyPath] let valid = validateDependency(dependency) if !valid { context.error("Invalid \(dependency): \(error)") } } } /// validate some properties on state by returning a boolean public func validateState(_ name: String, file: StaticString = #filePath, line: UInt = #line, _ validateState: @escaping (Model.State) -> Bool) -> Self { addExpectation(title: "Validate", details: name, file: file, line: line) { context in let valid = validateState(context.model.state) if !valid { context.error("Invalid State \(name.quoted)") } } } /// expect state to have certain properties set. Set any properties on the state that should be set. Any properties left out fill not fail the test public func expectState(file: StaticString = #filePath, line: UInt = #line, _ modify: @escaping (inout Model.State) -> Void) -> Self { addExpectation(title: "Expect State", file: file, line: line) { context in let currentState = context.model.state var expectedState = currentState modify(&expectedState) modify(&context.testContext.state) if let difference = StateDump.diff(expectedState, currentState) { context.error("Unexpected State", diff: difference) } } } // Used for getters /// expect state to have a keypath set to a value. public func expectState<Value>(_ keyPath: KeyPath<Model.State, Value>, _ value: Value, file: StaticString = #filePath, line: UInt = #line) -> Self { addExpectation(title: "Expect \(keyPath.propertyName ?? "State")", file: file, line: line) { context in let currentState = context.model.state[keyPath: keyPath] if let difference = StateDump.diff(value, currentState) { context.error("Unexpected \(keyPath.propertyName?.quoted ?? "State")", diff: difference) } } } // Used for instance variables /// expect state to have a keypath set to a value. public func expectState<Value>(_ keyPath: WritableKeyPath<Model.State, Value>, _ value: Value, file: StaticString = #filePath, line: UInt = #line) -> Self { addExpectation(title: "Expect \(keyPath.propertyName ?? "State")", file: file, line: line) { context in let currentState = context.model.state var expectedState = currentState expectedState[keyPath: keyPath] = value context.testContext.state[keyPath: keyPath] = value if let difference = StateDump.diff(expectedState, currentState) { context.error("Unexpected \(keyPath.propertyName?.quoted ?? "State")", diff: difference) } } } /// expect environment to have a keypath set to a value. public func expectEnvironment<Value>(_ keyPath: KeyPath<Model.Environment, Value>, _ value: Value, file: StaticString = #filePath, line: UInt = #line) -> Self { addExpectation(title: "Expect environment \(keyPath.propertyName ?? "State")", file: file, line: line) { context in let currentState = context.model.environment[keyPath: keyPath] if let difference = StateDump.diff(value, currentState) { context.error("Unexpected environment \(keyPath.propertyName?.quoted ?? "State")", diff: difference) } } } }
yonaskolb/SwiftComponent
16
Where architecture meets tooling
Swift
yonaskolb
Yonas Kolb
Sources/SwiftComponent/Testing/TestResult.swift
Swift
import Foundation public struct TestStepResult: Identifiable { public var id: UUID public var title: String public var details: String? public var expectations: [String] public var events: [Event] public var stepErrors: [TestError] public var expectationErrors: [TestError] public var assertionErrors: [TestError] public var assertionWarnings: [TestError] public var errors: [TestError] { stepErrors + expectationErrors + assertionErrors } public var allErrors: [TestError] { errors + children.reduce([]) { $0 + $1.allErrors } } public var allWarnings: [TestError] { assertionWarnings + children.reduce([]) { $0 + $1.allWarnings } } public var children: [TestStepResult] public var success: Bool { allErrors.isEmpty } public var coverage: TestCoverage init<Model>( step: TestStep<Model>, events: [Event], expectationErrors: [TestError], assertionErrors: [TestError], assertionWarnings: [TestError], children: [TestStepResult], coverage: TestCoverage ) { self.id = step.id self.title = step.title self.details = step.details self.expectations = step.expectations.map(\.description) self.events = events self.expectationErrors = expectationErrors self.assertionErrors = assertionErrors self.assertionWarnings = assertionWarnings self.children = children self.stepErrors = [] self.coverage = coverage } public var description: String { var string = title if let details { string += " \(details)" } return string } public var mutations: [Mutation] { events.compactMap { event in switch event.type { case .mutation(let mutation): return mutation default: return nil } } } } public struct TestResult<Model: ComponentModel> { public var start: Date public var end: Date public var steps: [TestStepResult] public var success: Bool { errors.isEmpty && steps.allSatisfy(\.success) } public var stepErrors: [TestError] { steps.reduce([]) { $0 + $1.errors } } public var errors: [TestError] { stepErrors } public var snapshots: [ComponentSnapshot<Model>] public var duration: TimeInterval { end.timeIntervalSince1970 - start.timeIntervalSince1970 } public var formattedDuration: String { let seconds = duration if seconds < 2 { return Int(seconds*1000).formatted(.number) + " ms" } else { return (start ..< end).formatted(.components(style: .abbreviated)) } } } public struct TestCoverage { public var actions: Set<String> = [] public var outputs: Set<String> = [] public var routes: Set<String> = [] public var dependencies: Set<String> = [] var hasValues: Bool { !actions.isEmpty || !outputs.isEmpty || !routes.isEmpty || !dependencies.isEmpty } mutating func subtract(_ coverage: TestCoverage) { actions.subtract(coverage.actions) outputs.subtract(coverage.outputs) routes.subtract(coverage.routes) dependencies.subtract(coverage.dependencies) } mutating func add(_ coverage: TestCoverage) { actions.formUnion(coverage.actions) outputs.formUnion(coverage.outputs) routes.formUnion(coverage.routes) dependencies.formUnion(coverage.dependencies) } } public struct TestError: CustomStringConvertible, Identifiable, Hashable { public var error: String public var diff: [String]? public let source: Source public var fixit: String? public let id = UUID() public init(error: String, diff: [String]? = nil, source: Source, fixit: String? = nil) { self.error = error self.diff = diff self.source = source self.fixit = fixit } public var description: String { var string = error if let diff { string += ":\n\(diff.joined(separator: "\n"))" } return string } }
yonaskolb/SwiftComponent
16
Where architecture meets tooling
Swift
yonaskolb
Yonas Kolb
Sources/SwiftComponent/Testing/TestRun.swift
Swift
// // File.swift // // // Created by Yonas Kolb on 20/3/2023. // import Foundation import SwiftUI @_implementationOnly import Runtime struct TestRun<ComponentType: Component> { typealias Model = ComponentType.Model var testState: [Test<ComponentType>.ID: TestState] = [:] var testResults: [Test<ComponentType>.ID: [TestStep<Model>.ID]] = [:] var testStepResults: [TestStep<Model>.ID: TestStepResult] = [:] var snapshots: [String: ComponentSnapshot<Model>] = [:] var testCoverage: TestCoverage = .init() var missingCoverage: TestCoverage = .init() var totalCoverage: TestCoverage = .init() var passedStepCount: Int { testStepResults.values.filter { $0.success }.count } var failedStepCount: Int { testStepResults.values.filter { !$0.success }.count } var totalStepCount: Int { testStepResults.values.count } var passedTestCount: Int { testState.values.filter { $0.passed }.count } var failedTestCount: Int { testState.values.filter { $0.failed }.count } var stepWarningsCount: Int { testState.values.reduce(0) { $0 + $1.warningCount } } func getTestState(_ test: Test<ComponentType>) -> TestState { testState[test.id] ?? .notRun } mutating func reset(_ tests: [Test<ComponentType>]) { testState = [:] testResults = [:] testStepResults = [:] for test in tests { testState[test.id] = .pending } } mutating func startTest(_ test: Test<ComponentType>) { testState[test.id] = .running testResults[test.id] = [] } mutating func addStepResult(_ result: TestStepResult, test: Test<ComponentType>) { testResults[test.id, default: []].append(result.id) testStepResults[result.id] = result } mutating func completeTest(_ test: Test<ComponentType>, result: TestResult<Model>) { testState[test.id] = .complete(result) for snapshot in result.snapshots { snapshots[snapshot.name] = snapshot } } mutating func checkCoverage() { var testCoverage: TestCoverage = .init() var missingCoverage: TestCoverage = .init() var totalCoverage: TestCoverage = .init() for stepResult in testStepResults.values { testCoverage.add(stepResult.coverage) } func checkCovereage<ModelType>(_ keyPath: WritableKeyPath<TestCoverage, Set<String>>, type: ModelType.Type) { if let typeInfo = try? typeInfo(of: type), typeInfo.kind == .enum { totalCoverage[keyPath: keyPath] = Set(typeInfo.cases.map(\.name)) } } checkCovereage(\.actions, type: Model.Action.self) checkCovereage(\.outputs, type: Model.Output.self) checkCovereage(\.routes, type: Model.Route.self) missingCoverage = totalCoverage missingCoverage.subtract(testCoverage) self.missingCoverage = missingCoverage self.testCoverage = testCoverage self.totalCoverage = totalCoverage } func getTestResults(for tests: [Test<ComponentType>]) -> [TestStepResult] { var results: [TestStepResult] = [] for test in tests { let steps = testResults[test.id] ?? [] for stepID in steps { if let result = testStepResults[stepID] { results.append(contentsOf: getTestResults(for: result)) } } } return results } private func getTestResults(for testResult: TestStepResult) -> [TestStepResult] { var results: [TestStepResult] = [testResult] for child in testResult.children { results.append(contentsOf: getTestResults(for: child)) } return results } enum TestState { case notRun case running case failedToRun(TestError) case complete(TestResult<Model>) case pending var passed: Bool { switch self { case .complete(let result): return result.success default: return false } } var failed: Bool { switch self { case .complete(let result): return !result.success case .failedToRun: return true default: return false } } var warningCount: Int { switch self { case .complete(let result): return result.steps.reduce(0) { $0 + $1.allWarnings.count } default: return 0 } } var errors: [TestError]? { switch self { case .complete(let result): let errors = result.errors if !errors.isEmpty { return errors} case .failedToRun(let error): return [error] default: break } return nil } var color: Color { switch self { case .notRun: return .accentColor case .running: return .gray case .failedToRun: return .red case .complete(let result): return result.success ? .green : .red case .pending: return .gray } } } }
yonaskolb/SwiftComponent
16
Where architecture meets tooling
Swift
yonaskolb
Yonas Kolb
Sources/SwiftComponent/Testing/TestRunner.swift
Swift
import Foundation @_implementationOnly import Runtime @MainActor public struct TestContext<Model: ComponentModel> { public let model: ViewModel<Model> public var delay: TimeInterval public var assertions: [TestAssertion] public var runAssertions: Bool = true public var runExpectations: Bool = true public var collectTestCoverage: Bool = true public var childStepResults: [TestStepResult] = [] public var stepErrors: [TestError] = [] public var testCoverage: TestCoverage = .init() var snapshots: [ComponentSnapshot<Model>] = [] var state: Model.State var delayNanoseconds: UInt64 { UInt64(1_000_000_000.0 * delay) } } extension Component { @MainActor public static func runTest( _ test: Test<Self>, model: ViewModel<Model>, initialState: Model.State? = nil, assertions: [TestAssertion], delay: TimeInterval = 0, onlyCollectSnapshots: Bool = false, sendEvents: Bool = false, stepComplete: ((TestStepResult) -> Void)? = nil ) async -> TestResult<Model> { await TestRunTask.$running.withValue(true) { let start = Date() let assertions = test.assertions ?? assertions model.store.dependencies.reset() model.store.dependencies.apply(test.dependencies) model.store.dependencies.dependencyValues.context = .preview model.store.children = [:] let sendEventsValue = model.store.sendGlobalEvents model.store.sendGlobalEvents = sendEvents defer { model.store.sendGlobalEvents = sendEventsValue } if delay > 0 { model.store.previewTaskDelay = delay } defer { model.store.previewTaskDelay = 0 } if let initialState { model.state = initialState } model.route = nil model.store.graph.clearRoutes() var stepResults: [TestStepResult] = [] var context = TestContext<Model>(model: model, delay: delay, assertions: assertions, state: model.state) if onlyCollectSnapshots { context.runExpectations = false context.collectTestCoverage = false context.runAssertions = false } for step in test.steps { context.stepErrors = [] var result = await TestStepID.$current.withValue(step.id) { await step.runTest(context: &context) } result.stepErrors.append(contentsOf: context.stepErrors) stepComplete?(result) stepResults.append(result) } return TestResult<Model>(start: start, end: Date(), steps: stepResults, snapshots: context.snapshots) } } } extension TestStep { @MainActor func runTest(context: inout TestContext<Model>) async -> TestStepResult { var stepEvents: [Event] = [] var unexpectedEvents: [Event] = [] context.state = context.model.state let previousChildStepResults = context.childStepResults context.childStepResults = [] defer { context.childStepResults = previousChildStepResults } let runAssertions = context.runAssertions let storeID = context.model.store.id let startingAccessedDependencies = context.model.store.dependencies.accessedDependencies context.model.store.dependencies.accessedDependencies = [] let stepEventsSubscription = context.model.store.events.sink { event in // TODO: should probably check id instead if event.storeID == storeID { stepEvents.append(event) unexpectedEvents.append(event) } } _ = stepEventsSubscription // hide warning await withDependencies { dependencyValues in dependencyValues = context.model.store.dependencies.dependencyValues } operation: { @MainActor in await self.run(&context) } var testCoverage = TestCoverage() if context.collectTestCoverage { let checkActions = (try? typeInfo(of: Model.Action.self))?.kind == .enum let checkOutputs = (try? typeInfo(of: Model.Output.self))?.kind == .enum let checkRoutes = (try? typeInfo(of: Model.Route.self))?.kind == .enum for event in stepEvents where event.path == context.model.path { switch event.type { case .action(let action): if checkActions { testCoverage.actions.insert(getEnumCase(action).name) } case .output(let output): if checkOutputs { testCoverage.outputs.insert(getEnumCase(output).name) } case .route(let route): if checkRoutes { testCoverage.routes.insert(getEnumCase(route).name) } default: break } } testCoverage.dependencies = context.model.store.dependencies.accessedDependencies context.model.store.dependencies.accessedDependencies = startingAccessedDependencies.union(testCoverage.dependencies) context.testCoverage.add(testCoverage) } var expectationErrors: [TestError] = [] if context.runExpectations { for expectation in expectations { var expectationContext = TestExpectation<Model>.Context(testContext: context, source: expectation.source, events: unexpectedEvents) expectation.run(&expectationContext) unexpectedEvents = expectationContext.events context.state = expectationContext.testContext.state expectationErrors += expectationContext.errors } } var assertionErrors: [TestError] = [] var assertionWarnings: [TestError] = [] if context.runAssertions { for assertion in context.assertions { var assertionContext = TestAssertionContext(events: unexpectedEvents, source: source, testContext: context, stepID: self.id) assertion.assert(context: &assertionContext) assertionErrors += assertionContext.errors } for assertion in [TestAssertion].all { if !context.assertions.contains(where: { $0.id == assertion.id }) { var assertionContext = TestAssertionContext(events: unexpectedEvents, source: source, testContext: context, stepID: self.id) assertion.assert(context: &assertionContext) assertionWarnings += assertionContext.errors } } } context.runAssertions = runAssertions return TestStepResult( step: self, events: stepEvents, expectationErrors: expectationErrors, assertionErrors: assertionErrors, assertionWarnings: assertionWarnings, children: context.childStepResults, coverage: testCoverage ) } } extension Component { @MainActor public static func run(_ test: Test<Self>, assertions: [TestAssertion]? = nil, onlyCollectSnapshots: Bool = false) async -> TestResult<Model> { return await withDependencies { // standardise context, and prevent failures in unit tests, as dependency tracking is handled within $0.context = .preview } operation: { let model = ViewModel<Model>(state: test.state, environment: test.environment) return await runTest( test, model: model, assertions: assertions ?? testAssertions, onlyCollectSnapshots: onlyCollectSnapshots ) } } } public enum TestRunTask { @TaskLocal public static var running = false }
yonaskolb/SwiftComponent
16
Where architecture meets tooling
Swift
yonaskolb
Yonas Kolb
Sources/SwiftComponent/Testing/TestStep.swift
Swift
import Foundation public typealias TestStepContext<Model: ComponentModel> = TestStep<Model> public typealias Step = TestStep public enum TestStepID { @TaskLocal public static var current = UUID() } public struct TestStep<Model: ComponentModel>: Identifiable { public var title: String public var details: String? public var source: Source public let id = UUID() public var expectations: [TestExpectation<Model>] = [] var dependencies: ComponentDependencies var snapshots: [TestSnapshot] = [] fileprivate var _run: @MainActor (inout TestContext<Model>) async -> Void public init(title: String, details: String? = nil, file: StaticString, line: UInt, run: @escaping @MainActor (inout TestContext<Model>) async -> Void) { self.title = title self.details = details self.source = .capture(file: file, line: line) self._run = run self.dependencies = .init() } @MainActor public func run(_ context: inout TestContext<Model>) async { await _run(&context) } public var description: String { var string = title if let details { string += " \(details)" } return string } } extension TestStep { public func beforeRun(_ run: @MainActor @escaping (inout TestContext<Model>) async -> Void, file: StaticString = #filePath, line: UInt = #line) -> Self { var step = self let stepRun = _run step._run = { context in await run(&context) await stepRun(&context) } return step } public func afterRun(_ run: @MainActor @escaping (inout TestContext<Model>) async -> Void, file: StaticString = #filePath, line: UInt = #line) -> Self { var step = self let stepRun = _run step._run = { context in await stepRun(&context) await run(&context) } return step } } // Type inference in builders doesn't work properly // https://forums.swift.org/t/function-builder-cannot-infer-generic-parameters-even-though-direct-call-to-buildblock-can/35886/25 // https://forums.swift.org/t/result-builder-expressiveness-and-type-inference/56417 @resultBuilder public struct TestStepBuilder<Model: ComponentModel> { public static func buildExpression(_ steps: TestStep<Model>) -> TestStep<Model> { steps } public static func buildExpression(_ steps: [TestStep<Model>]) -> [TestStep<Model>] { steps } public static func buildPartialBlock(first: TestStep<Model>) -> [TestStep<Model>] { [first] } public static func buildPartialBlock(first: [TestStep<Model>]) -> [TestStep<Model>] { first } public static func buildPartialBlock(first: [[TestStep<Model>]]) -> [TestStep<Model>] { first.flatMap { $0 } } public static func buildPartialBlock(accumulated: [TestStep<Model>], next: TestStep<Model>) -> [TestStep<Model>] { accumulated + [next] } public static func buildPartialBlock(accumulated: [TestStep<Model>], next: [TestStep<Model>]) -> [TestStep<Model>] { accumulated + next } public static func buildPartialBlock(accumulated: [TestStep<Model>], next: [[TestStep<Model>]]) -> [TestStep<Model>] { accumulated + next.flatMap { $0 } } }
yonaskolb/SwiftComponent
16
Where architecture meets tooling
Swift
yonaskolb
Yonas Kolb
Sources/SwiftComponent/Testing/TestSteps.swift
Swift
import Foundation import SwiftUI extension TestStep { public static func run(_ title: String, file: StaticString = #filePath, line: UInt = #line, _ run: @escaping () async -> Void) -> Self { .init(title: title, file: file, line: line) { _ in await run() } } public static func appear(first: Bool = true, await: Bool = true, file: StaticString = #filePath, line: UInt = #line) -> Self { .init(title: "Appear", file: file, line: line) { context in if `await` { await context.model.appearAsync(first: first, file: file, line: line) } else { context.model.appear(first: first, file: file, line: line) } } } public static func disappear(file: StaticString = #filePath, line: UInt = #line) -> Self { .init(title: "Disappear", file: file, line: line) { context in context.model.disappear(file: file, line: line) } } public static func action(_ action: Model.Action, file: StaticString = #filePath, line: UInt = #line) -> Self { .init(title: "Send Action", details: getEnumCase(action).name, file: file, line: line) { context in if context.delay > 0 { try? await Task.sleep(nanoseconds: context.delayNanoseconds) } await context.model.store.processAction(action, source: .capture(file: file, line: line)) } } public static func input(_ input: Model.Input, file: StaticString = #filePath, line: UInt = #line) -> Self { .init(title: "Recieve Input", details: getEnumCase(input).name, file: file, line: line) { context in if context.delay > 0 { try? await Task.sleep(nanoseconds: context.delayNanoseconds) } await context.model.store.processInput(input, source: .capture(file: file, line: line)) } } public static func binding<Value>(_ keyPath: WritableKeyPath<Model.State, Value>, _ value: Value, animated: Bool = true, file: StaticString = #filePath, line: UInt = #line) -> Self { .init(title: "Set Binding", details: "\(keyPath.propertyName ?? "value") = \(value)", file: file, line: line) { context in if animated, let string = value as? String, string.count > 1, string != "", context.delay > 0 { let sleepTime = Double(context.delayNanoseconds)/(Double(string.count)) var currentString = "" for character in string.dropLast(1) { currentString.append(character) context.model.store.state[keyPath: keyPath] = currentString as! Value if sleepTime > 0 { try? await Task.sleep(nanoseconds: UInt64(sleepTime)) } } } else if context.delay > 0 { try? await Task.sleep(nanoseconds: context.delayNanoseconds) } context.state[keyPath: keyPath] = value await context.model.store.setBinding(keyPath, value) } } public static func binding<Value>(_ keyPath: WritableKeyPath<Model.State, Value?>, _ value: Value?, animated: Bool = true, file: StaticString = #filePath, line: UInt = #line) -> Self { .init(title: "Set Binding", details: "\(keyPath.propertyName ?? "value") = \(value != nil ? String(describing: value!) : "nil")", file: file, line: line) { context in if animated, let string = value as? String, string.count > 1, string != "", context.delay > 0 { let sleepTime = Double(context.delayNanoseconds)/(Double(string.count)) var currentString = "" for character in string { currentString.append(character) context.model.store.state[keyPath: keyPath] = currentString as? Value if sleepTime > 0 { try? await Task.sleep(nanoseconds: UInt64(sleepTime)) } } } else if context.delay > 0 { try? await Task.sleep(nanoseconds: context.delayNanoseconds) } context.state[keyPath: keyPath] = value await context.model.store.setBinding(keyPath, value) } } public static func dependency<T>(_ keyPath: WritableKeyPath<DependencyValues, T>, _ dependency: T, file: StaticString = #filePath, line: UInt = #line) -> Self { .init(title: "Set Dependency", details: keyPath.propertyName ?? "\(String(describing: Swift.type(of: dependency)))", file: file, line: line) { context in context.model.store.dependencies.setDependency(keyPath, dependency) } } public static func route<Child: ComponentModel>(_ path: CasePath<Model.Route, ComponentRoute<Child>>, file: StaticString = #filePath, line: UInt = #line, @TestStepBuilder<Child> _ steps: @escaping () -> [TestStep<Child>]) -> Self { .steps(title: "Route", details: "\(Child.baseName)", file: file, line: line, steps: steps) { context in guard let componentRoute = context.getRoute(path, source: .capture(file: file, line: line)) else { return nil } if context.delay > 0 { try? await Task.sleep(nanoseconds: context.delayNanoseconds) try? await Task.sleep(nanoseconds: UInt64(1_000_000_000.0 * 0.35)) // wait for typical presentation animation duration } return componentRoute.model } } public static func route<Child: ComponentModel>(_ path: CasePath<Model.Route, ComponentRoute<Child>>, output: Child.Output, file: StaticString = #filePath, line: UInt = #line) -> Self { .init(title: "Route Output", details: "\(Child.baseName).\(getEnumCase(output).name)", file: file, line: line) { context in guard let componentRoute = context.getRoute(path, source: .capture(file: file, line: line)) else { return } await componentRoute.model.store.output(output, source: .capture(file: file, line: line)) await Task.yield() if context.delay > 0 { try? await Task.sleep(nanoseconds: context.delayNanoseconds) try? await Task.sleep(nanoseconds: UInt64(1_000_000_000.0 * 0.35)) // wait for typical presentation animation duration } } } public static func dismissRoute(file: StaticString = #filePath, line: UInt = #line) -> Self { .init(title: "Dimiss Route", file: file, line: line) { context in context.model.store.dismissRoute(source: .capture(file: file, line: line)) await Task.yield() if context.delay > 0 { try? await Task.sleep(nanoseconds: context.delayNanoseconds) try? await Task.sleep(nanoseconds: UInt64(1_000_000_000.0 * 0.35)) // wait for typical presentation animation duration } } } // TODO: support snapshots by making connenctions bi-directoional or removing type from Snapshot public static func scope<Child: ComponentModel>(_ connection: ComponentConnection<Model, Child>, file: StaticString = #filePath, line: UInt = #line, @TestStepBuilder<Child> steps: @escaping () -> [TestStep<Child>]) -> Self { .init(title: "Scope", details: Child.baseName, file: file, line: line) { context in //TODO: get the model that the view is using so it can playback in the preview let viewModel = connection.convert(context.model) let steps = steps() var childContext = TestContext<Child>(model: viewModel, delay: context.delay, assertions: context.assertions, state: viewModel.state) for step in steps { let results = await step.runTest(context: &childContext) context.childStepResults.append(results) } } } public static func branch(_ name: String, file: StaticString = #filePath, line: UInt = #line, @TestStepBuilder<Model> steps: @escaping () -> [TestStep<Model>]) -> Self { let steps = steps() let snapshots = steps.flatMap(\.snapshots) var step = TestStep<Model>(title: "Branch", details: name, file: file, line: line) { context in if context.delay > 0 { try? await Task.sleep(nanoseconds: context.delayNanoseconds) } let state = context.model.state let route = context.model.route let children = context.model.store.children let dependencyValues = context.model.dependencies.dependencyValues let cancelledTasks = context.model.store.cancelledTasks let environment = context.model.environment context.model.store.environment = environment.copy() for step in steps { let results = await step.runTest(context: &context) context.childStepResults.append(results) } // reset state context.model.state = state context.state = state context.model.route = route context.model.dependencies.setValues(dependencyValues) context.model.store.children = children context.model.store.cancelledTasks = cancelledTasks context.model.store.environment = environment // don't assert on this step context.runAssertions = false if context.delay > 0 { try? await Task.sleep(nanoseconds: context.delayNanoseconds) } } step.snapshots = snapshots return step } } // MARK: Helpers extension TestStep { static func steps<Child: ComponentModel>( title: String, details: String?, file: StaticString = #filePath, line: UInt = #line, steps: @escaping () -> [TestStep<Child>], createModel: @MainActor @escaping (inout TestContext<Model>) async -> ViewModel<Child>? ) -> Self { .init( title: title, details: details, file: file, line: line ) { context in guard let model = await createModel(&context) else { return } let steps = steps() var childContext = TestContext<Child>(model: model, delay: context.delay, assertions: context.assertions, state: model.state) for step in steps { let results = await step.runTest(context: &childContext) context.childStepResults.append(results) } } } } extension TestContext { mutating func getRoute<Child: ComponentModel>(_ path: CasePath<Model.Route, ComponentRoute<Child>>, source: Source) -> ComponentRoute<Child>? { guard let route = model.store.route else { stepErrors = [TestError(error: "Couldn't route to \(Child.baseName)", source: source)] return nil } guard let componentRoute = path.extract(from: route) else { stepErrors = [TestError(error: "Couldn't route to \(Child.baseName)", source: source)] return nil } return componentRoute } }
yonaskolb/SwiftComponent
16
Where architecture meets tooling
Swift
yonaskolb
Yonas Kolb
Sources/SwiftComponent/UI/ComponentDashboardView.swift
Swift
import Foundation import SwiftUI import SwiftPreview import SwiftGUI @MainActor struct ComponentDashboardView<ComponentType: Component>: View { var model: ViewModel<ComponentType.Model> @AppStorage("componentPreview.showView") var showView = true @AppStorage("componentPreview.showComponent") var showComponent = true @AppStorage("previewTests") var previewTests = true @Environment(\.colorScheme) var colorScheme: ColorScheme @State var showTestEvents = true @State var autoRunTests = true @State var testRun: TestRun<ComponentType> = TestRun() @State var runningTests = false @State var render = UUID() @State var previewTestDelay = 0.4 @State var showEvents: Set<EventSimpleType> = Set(EventSimpleType.allCases)//.subtracting([.mutation, .binding]) var events: [Event] { EventStore.shared.events } var snapshots: [ComponentSnapshot<ComponentType.Model>] { ComponentType.snapshots + ComponentType.testSnapshots.compactMap { testRun.snapshots[$0.name] } } func stateBinding() -> Binding<ComponentType.Model.State> { Binding( get: { model.state }, set: { state in model.state = state } ) } func clearEvents() { EventStore.shared.clear() render = UUID() } func runAllTests(delay: TimeInterval) { Task { @MainActor in await runAllTestsOnMain(delay: delay) } } func runAllTestsOnMain(delay: TimeInterval) async { testRun.reset(ComponentType.tests) for test in ComponentType.tests { await runTest(test, delay: delay) } } func runTest(_ test: Test<ComponentType>, delay: TimeInterval) async { runningTests = true testRun.startTest(test) let model: ViewModel<ComponentType.Model> if delay > 0 { model = self.model } else { model = ViewModel(state: test.state, environment: test.environment) } let result = await ComponentType.runTest( test, model: model, initialState: test.state, assertions: ComponentType.testAssertions, delay: delay, sendEvents: delay > 0 && showTestEvents ) testRun.completeTest(test, result: result) runningTests = false } func selectTest(_ test: Test<ComponentType>) { clearEvents() Task { @MainActor in await runTest(test, delay: previewTestDelay) } } func selectSnapshot(_ snapshot: ComponentSnapshot<ComponentType.Model>) { withAnimation { model.state = snapshot.state model.store.environment = snapshot.environment model.store.dependencies.apply(snapshot.dependencies) model.store.model.updateView() // in case state hasn't changed but dependencies uses in rendering have if let route = snapshot.route { model.store.present(route, source: .capture()) } else { model.store.dismissRoute(source: .capture()) } } } var body: some View { HStack(spacing: 0) { if showComponent { NavigationView { form .navigationTitle(String(describing: ComponentType.self)) #if os(iOS) .navigationBarTitleDisplayMode(.inline) #endif } #if os(iOS) .navigationViewStyle(.stack) #endif .frame(maxWidth: .infinity) } Divider() if showView { ComponentType.view(model: model) .preview() .frame(maxWidth: .infinity, maxHeight: .infinity) .background(colorScheme == .light ? Color(white: 0.95) : Color.black) // match form background } } .task { runAllTests(delay: 0) } // .toolbar { // ToolbarItem(placement: .navigationBarLeading) { // Button(action: { withAnimation { // showView.toggle() // if !showComponent && !showView { // showComponent = true // } // // }}) { // Image(systemName: "rectangle.leadinghalf.inset.filled") // Text("View") // } // } // ToolbarItem(placement: .navigationBarTrailing) { // Button(action: { withAnimation { // showComponent.toggle() // if !showComponent && !showView { // showView = true // } // }}) { // Text("Model") // Image(systemName: "rectangle.trailinghalf.inset.filled") // } // } // } } var form: some View { Form { if !(ComponentType.Model.State.self == Void.self) { stateSection } if !snapshots.isEmpty { snapshotsSection } routeSection if !ComponentType.tests.isEmpty { // testSettingsSection testSection } eventsSection } .animation(.default, value: events.count + (model.route == nil ? 1 : 0)) } var testSettingsSection: some View { Section(header: Text("Test Settings")) { Toggle("Auto Run Tests", isOn: $autoRunTests) Toggle("Preview Tests", isOn: $previewTests) Toggle("Show Test Events", isOn: $showTestEvents) } } var snapshotsSection: some View { Section(header: Text("Snapshots")) { ForEach(snapshots, id: \.name) { snapshot in Button { selectSnapshot(snapshot) } label: { Text(snapshot.name) } } } } var stateSection: some View { Section(header: Text("State")) { SwiftView(value: stateBinding(), config: Config(editing: true, propertyFilter: Config.prettyPropertyFilter)) .showRootNavTitle(false) } } @ViewBuilder var routeSection: some View { if ComponentType.Model.Route.self != Never.self { Section(header: Text("Route")) { if let route = model.route { HStack { Text(getEnumCase(route).name) Spacer() Button(action: { withAnimation { model.route = nil } }) { Text("Dismiss") } } } else { Text("none") } } } } var testSection: some View { Section(header: testHeader) { ForEach(ComponentType.tests, id: \.id) { test in let testResult = testRun.getTestState(test) VStack(alignment: .leading, spacing: 8) { Button { selectTest(test) } label: { VStack(alignment: .leading) { HStack(spacing: 8) { ZStack { ProgressView().hidden() switch testResult { case .running: ProgressView().progressViewStyle(CircularProgressViewStyle()) case .failedToRun: Image(systemName: "exclamationmark.circle.fill").foregroundColor(.red) case .complete(let result): if result.success { Image(systemName: "checkmark.circle.fill").foregroundColor(.green) } else { Image(systemName: "exclamationmark.circle.fill").foregroundColor(.red) } case .notRun: Image(systemName: "circle") case .pending: Image(systemName: "play.circle").foregroundColor(.gray) } } .foregroundColor(testResult.color) Text(test.testName) .foregroundColor(testResult.color) Spacer() if let error = testResult.errors?.first { Text(error.error).foregroundColor(.red) .lineLimit(1) } Image(systemName: "play.circle") .font(.title3) .disabled(runningTests) } .animation(nil) if let error = testResult.errors?.first { VStack(alignment: .leading) { // Text(error.error) // .foregroundColor(.red) // .lineLimit(1) // .padding(.leading, 20) if let diff = error.diff { VStack(alignment: .leading) { diff .diffText() .frame(maxWidth: .infinity, alignment: .leading) .textContainer() .cornerRadius(8) } .padding(4) } } } } } } } } .disabled(runningTests) } var testHeader: some View { HStack { Text("Tests") Spacer() Button { runAllTests(delay: previewTestDelay) } label: { Text("Play all") } .buttonStyle(.plain) } } var eventsSection: some View { Section(header: eventsHeader) { ComponentEventList( events: Array(events .filter { showEvents.contains($0.type.type) } .sorted { $0.start > $1.start } .prefix(500) ), allEvents: events.sorted { $0.start > $1.start }, indent: false) .id(render) } .onReceive(EventStore.shared.eventPublisher) { _ in render = UUID() } } var eventsHeader: some View { HStack { Text("Events") Spacer() Button(action: clearEvents) { Text("Clear") } .buttonStyle(.plain) } } } struct ComponentDashboard_Previews: PreviewProvider { static var previews: some View { NavigationView { ComponentDashboardView<ExampleComponent>(model: ExampleComponent.previewModel()) } #if os(iOS) .navigationViewStyle(.stack) #endif .largePreview() } }
yonaskolb/SwiftComponent
16
Where architecture meets tooling
Swift
yonaskolb
Yonas Kolb
Sources/SwiftComponent/UI/ComponentDebugView.swift
Swift
import SwiftUI import SwiftGUI struct ComponentDebugSheet<Model: ComponentModel>: View { let model: ViewModel<Model> @Environment(\.dismiss) var dismiss var body: some View { NavigationView { ComponentDebugView(model: model) .toolbar { #if os(iOS) ToolbarItem(placement: .navigationBarTrailing) { Button(action: { dismiss ()}) { Text("Close") } } #endif } } } } public struct ComponentDebugView<Model: ComponentModel>: View { let model: ViewModel<Model> let editableState: Bool @State var eventTypes = EventSimpleType.set @AppStorage("showBindings") var showBindings = true @AppStorage("showChildEvents") var showChildEvents = true public init(model: ViewModel<Model>, editableState: Bool = true) { self.model = model self.editableState = editableState } func eventTypeBinding(_ event: EventSimpleType) -> Binding<Bool> { Binding( get: { eventTypes.contains(event) }, set: { if $0 { eventTypes.insert(event) } else { eventTypes.remove(event) } } ) } var events: [Event] { EventStore.shared.componentEvents(for: model.store.path, includeChildren: showChildEvents) .filter { eventTypes.contains($0.type.type) } .sorted { $0.start > $1.start } } public var body: some View { Form { if let parent = model.store.path.parent { Section(header: Text("Parent")) { Text(parent.string) .lineLimit(2) .truncationMode(.head) } } Section(header: Text("State")) { SwiftView(value: model.binding(\.self), config: Config(editing: editableState, propertyFilter: Config.prettyPropertyFilter)) .showRootNavTitle(false) } Section(header: eventsHeader) { Toggle("Show Child Events", isOn: $showChildEvents) NavigationLink { Form { ForEach(EventSimpleType.allCases, id: \.rawValue) { event in HStack { Circle().fill(event.color) .frame(width: 18) .padding(2) Text(event.title) Spacer() Toggle(isOn: eventTypeBinding(event)) { Text("") } } } } #if os(iOS) .navigationBarTitle(Text("Events")) #endif } label: { Text("Filter Event Types") } } Section { ComponentEventList( events: events, allEvents: EventStore.shared.events, indent: false) } } .animation(.default, value: eventTypes) .animation(.default, value: showChildEvents) .navigationTitle(model.componentName + " Component") #if os(iOS) .navigationBarTitleDisplayMode(.inline) #endif } var eventsHeader: some View { HStack { Text("Events") Spacer() Text(events.count.formatted()) } } var componentHeader: some View { Text(model.componentName) .bold() .textCase(.none) .font(.headline) .foregroundColor(.primary) } } extension ComponentView { func debugSheet() -> some View { ComponentDebugSheet(model: model) } } struct ComponentDebugView_Previews: PreviewProvider { static var previews: some View { EventStore.shared.events = previewEvents return ExampleView(model: .init(state: .init(name: "Hello"))) .debugSheet() #if os(iOS) .navigationViewStyle(.stack) #endif } }
yonaskolb/SwiftComponent
16
Where architecture meets tooling
Swift
yonaskolb
Yonas Kolb
Sources/SwiftComponent/UI/ComponentDescriptionView.swift
Swift
import Foundation import SwiftUI import SwiftPreview struct ComponentDescriptionView<ComponentType: Component>: View { var componentDescription: ComponentDescription = try! ComponentDescription(type: ComponentType.self) var maxPillWidth = 400.0 var body: some View { pills } var pills: some View { ScrollView { VStack { typeSection("Connections", icon: "arrow.left.arrow.right.square", componentDescription.model.connections) typeSection("State", icon: "square.text.square", componentDescription.model.state) typeSection("Action", icon: "arrow.up.square", componentDescription.model.action) typeSection("Input", icon: "arrow.forward.square", componentDescription.model.input) typeSection("Output", icon: "arrow.backward.square", componentDescription.model.output) typeSection("Route", icon: "arrow.uturn.right.square", componentDescription.model.route) // section("States", icon: "square.text.square", color: .teal) { // ForEach(componentDescription.component.states, id: \.self) { state in // Text(state) // .bold() // } // .item(color: .teal) // .frame(maxWidth: maxPillWidth) // } // .isUsed(!componentDescription.component.states.isEmpty) // section("Tests", icon: "checkmark.square", color: .teal) { // ForEach(componentDescription.component.tests, id: \.self) { test in // Text(test) // .bold() // } // .item(color: .teal) // .frame(maxWidth: maxPillWidth) // } // .isUsed(!componentDescription.component.tests.isEmpty) } .padding(20) } } func typeSection(_ name: String, icon: String, _ type: TypeDescription) -> some View { section(name, icon: icon) { typeView(type) .frame(maxWidth: maxPillWidth) } .isUsed(!type.isNever) } @ViewBuilder func typeView(_ type: TypeDescription) -> some View { switch type { case .enumType(let cases): ForEach(cases, id: \.name) { enumCase in HStack(alignment: .top) { Text(enumCase.name) .bold() Spacer() Text(enumCase.payloads.joined(separator: ", ")) .bold() .multilineTextAlignment(.trailing) } .item() .frame(maxWidth: maxPillWidth) } case .structType(let properties): ForEach(properties, id: \.name) { property in HStack(alignment: .top) { Text(property.name) .bold() Spacer() Text(property.type) .bold() .multilineTextAlignment(.trailing) } .item() .frame(maxWidth: maxPillWidth) } case .never: EmptyView() } } func section(_ name: String, icon: String, color: Color = .blue, @ViewBuilder content: () -> some View) -> some View { VStack(alignment: .leading) { HStack { Image(systemName: icon) Text(name) .bold() } .font(.title2) .padding(.bottom, 4) .foregroundColor(color) content() } .padding() // .foregroundColor(.blue) // .background { // RoundedRectangle(cornerRadius: 8).fill(Color.white.opacity(0.9)) // } } } fileprivate extension View { @ViewBuilder func isUsed(_ used: Bool) -> some View { if used { self } // self.opacity(used ? 1 : 0.2) } func item(color: Color = Color.blue.opacity(0.8)) -> some View { self .foregroundColor(.white) // .foregroundColor(.primary.opacity(0.6)) .padding(.vertical, 4) .padding(.horizontal, 8) .frame(maxWidth: .infinity, alignment: .leading) .background { RoundedRectangle(cornerRadius: 6).fill(color) } } func graphBackground() -> some View { self .padding(20) .foregroundColor(.white) .background { RoundedRectangle(cornerRadius: 12).fill(Color.blue) RoundedRectangle(cornerRadius: 12).stroke(Color.secondary.opacity(0.5)) } } } struct ComponentDescriptionView_Previews: PreviewProvider { static var previews: some View { ComponentDescriptionView<ExampleComponent>() // .previewDevice(.largestDevice) } }
yonaskolb/SwiftComponent
16
Where architecture meets tooling
Swift
yonaskolb
Yonas Kolb
Sources/SwiftComponent/UI/ComponentEditorView.swift
Swift
import SwiftUI import SwiftSyntax /** TODO: syntax highlighting TODO: proper editor with at least auto indent TODO: finer grained code blocks **/ struct ComponentEditorView<ComponentType: Component>: View { @State var initialFileContent: String = "" @State var fileContent: String = "" @State var modelBlock: Codeblock? @State var viewBlock: Codeblock? @State var componentBlock: Codeblock? @State var output = "" @State var showFile = false @State var hasChanges = false @State var sourceFileSyntax: SourceFileSyntax? let fileManager = FileManager.default func setup() { guard let source = ComponentType.readSource() else { return } fileContent = source initialFileContent = source let parser = CodeParser(source: source) sourceFileSyntax = parser.syntax modelBlock = parser.modelSource viewBlock = parser.viewSource componentBlock = parser.componentSource // output = parser.syntax.debugDescription(includeChildren: true) } func save() { guard var sourceFileSyntax else { return } let blocks = [ modelBlock, viewBlock, componentBlock, ] .compactMap { $0 } .filter(\.changed) let rewriter = CodeRewriter(blocks: blocks) sourceFileSyntax = rewriter.rewrite(sourceFileSyntax) let sourceCode = sourceFileSyntax.description ComponentType.writeSource(sourceCode) hasChanges = false } var body: some View { ZStack(alignment: .topTrailing) { VStack(alignment: .leading) { editors if output != "" { ScrollView { Text(output) } } } .padding() .padding(.top) if hasChanges { Button(action: save) { Text("Save") .font(.title) } .buttonStyle(.borderedProminent) .padding(.horizontal) } } .task { setup() } .ignoresSafeArea(.keyboard, edges: .bottom) } var wholeFile: some View { TextEditor(text: $fileContent) .frame(maxWidth: .infinity, alignment: .leading) .padding() .background { RoundedRectangle(cornerRadius: 3).stroke(Color.secondary.opacity(0.5)) } } var editors: some View { VStack(alignment: .leading, spacing: 24) { editor("Model", $modelBlock) editor("View", $viewBlock) editor("Component", $componentBlock) } } @ViewBuilder func editor(_ title: String, _ string: Binding<Codeblock?>) -> some View { VStack(alignment: .leading, spacing: 4) { Text(title) .bold() .font(.title2) .padding(.horizontal, 8) TextEditor(text: Binding( get: { string.wrappedValue?.source ?? ""}, set: { string.wrappedValue?.source = $0 hasChanges = true })) .autocorrectionDisabled(true) #if os(iOS) .textInputAutocapitalization(.never) #endif .colorScheme(.dark) .padding(.horizontal, 4) .background(.black) .cornerRadius(12) } } } struct ComponentEditorView_Previews: PreviewProvider { static var previews: some View { ComponentEditorView<ExampleComponent>() .largePreview() } }
yonaskolb/SwiftComponent
16
Where architecture meets tooling
Swift
yonaskolb
Yonas Kolb
Sources/SwiftComponent/UI/ComponentEventView.swift
Swift
import Foundation import SwiftUI import SwiftGUI struct ComponentEventList: View { let events: [Event] let allEvents: [Event] var depth: Int = 0 var indent = true @State var showEvent: UUID? @State var showMutation: UUID? func eventDepth(_ event: Event) -> Int { guard indent else { return 0 } return max(0, event.depth - depth) } var body: some View { ForEach(events) { event in NavigationLink(tag: event.id, selection: $showEvent, destination: { ComponentEventView(event: event, allEvents: allEvents) }) { VStack(alignment: .leading, spacing: 0) { HStack { // if eventDepth(event) > 0 { // Image(systemName: "arrow.turn.down.right") // .opacity(0.3) // .font(.system(size: 14)) // .padding(.top, 14) // } HStack(spacing: 6) { Circle() .fill(event.type.color) .frame(width: 12) Text(event.type.title) .bold() } Spacer() Text(event.type.details) .font(.footnote) } .font(.footnote) .padding(.top, 6) Text(event.path.string) .font(.caption2) .foregroundColor(.secondary) .lineLimit(1) .truncationMode(.middle) .padding(.leading, 18) } .padding(.leading, 8*Double(max(0, eventDepth(event)))) // inset children } } } } struct ComponentEventView: View { let event: Event var allEvents: [Event] var childEvents: [Event] { allEvents .filter { $0.start > event.start && $0.end < event.end } .sorted { $0.start < $1.start } } var parentEvents: [Event] { allEvents .filter { $0.start < event.start && $0.end > event.end } .sorted { $0.start < $1.start } } @State var showValue = false @State var showMutation: UUID? var body: some View { Form { if !event.type.detailsTitle.isEmpty || !event.type.details.isEmpty || !event.type.valueTitle.isEmpty { Section { if !event.type.detailsTitle.isEmpty || !event.type.details.isEmpty { line(event.type.detailsTitle) { Text(event.type.details) } } if !event.type.valueTitle.isEmpty { NavigationLink(isActive: $showValue) { SwiftView(value: .constant(event.type.value), config: Config(editing: false)) } label: { line(event.type.valueTitle) { Text(dumpLine(event.type.value)) .lineLimit(1) } } } } } Section { if let path = event.path.parent { line("Path") { Text(path.string) .lineLimit(1) .truncationMode(.head) } } line("Component") { Text(event.componentName) } line("Started") { Text(event.start.formatted()) } line("Duration") { Text(event.formattedDuration) } line("Location") { Text(verbatim: "\(event.source.file)#\(event.source.line.formatted())") .lineLimit(1) .truncationMode(.head) } // line("Depth") { // Text(event.depth.formatted()) // } } if !parentEvents.isEmpty { Section("Parents") { ComponentEventList(events: parentEvents, allEvents: allEvents, depth: 0) } } if !childEvents.isEmpty { Section("Children") { ComponentEventList(events: childEvents, allEvents: allEvents, depth: event.depth + 1) } } switch event.type { case .mutation(let mutation), .binding(let mutation): if let diff = mutation.stateDiff { Section("Mutation") { diff.diffText(textColor: .secondary) } } default: EmptyView() } } .navigationTitle(Text(event.type.title)) #if os(iOS) .navigationBarTitleDisplayMode(.inline) #endif } func line<Content: View>(_ name: String, content: () -> Content) -> some View { HStack { Text(name) .bold() Spacer() content() } } } let previewEvents: [Event] = [ Event( type: .view(.appear(first: true)), storeID: UUID(), componentPath: .init([ExampleModel.self]), start: Date().addingTimeInterval(-1.05), end: Date(), mutations: [ Mutation(keyPath: \ExampleModel.State.name, value: "new1", oldState: ExampleModel.State(name: "old1")), Mutation(keyPath: \ExampleModel.State.name, value: "new2", oldState: ExampleModel.State(name: "old2")), ], depth: 0, source: .capture() ), Event( type: .action(ExampleModel.Action.tap(2)), storeID: UUID(), componentPath: .init([ExampleModel.self, ExampleChildModel.self]), start: Date(), end: Date(), mutations: [ Mutation(keyPath: \ExampleModel.State.name, value: "new1", oldState: ExampleModel.State(name: "old1")), Mutation(keyPath: \ExampleModel.State.name, value: "new2", oldState: ExampleModel.State(name: "old2")), ], depth: 0, source: .capture() ), Event( type: .binding(Mutation(keyPath: \ExampleModel.State.name, value: "Hello", oldState: ExampleModel.State(name: "old1"))), storeID: UUID(), componentPath: .init(ExampleModel.self), start: Date(), end: Date(), mutations: [Mutation(keyPath: \ExampleModel.State.name, value: "Hello", oldState: ExampleModel.State(name: "old1"))], depth: 1, source: .capture() ), Event( type: .mutation(Mutation(keyPath: \ExampleModel.State.name, value: "Hello", oldState: ExampleModel.State(name: "old1"))), storeID: UUID(), componentPath: .init(ExampleModel.self), start: Date(), end: Date(), mutations: [Mutation(keyPath: \ExampleModel.State.name, value: "Hello", oldState: ExampleModel.State(name: "old1"))], depth: 2, source: .capture() ), Event( type: .task(TaskResult.init(name: "get item", result: .success(()))), storeID: UUID(), componentPath: .init(ExampleModel.self), start: Date().addingTimeInterval(-2.3), end: Date(), mutations: [], depth: 0, source: .capture() ), Event( type: .output(ExampleModel.Output.finished), storeID: UUID(), componentPath: .init(ExampleModel.self), start: Date(), end: Date(), mutations: [], depth: 2, source: .capture() ), ] struct EventView_Previews: PreviewProvider { static var previews: some View { EventStore.shared.events = previewEvents return Group { NavigationView { ComponentEventView(event: previewEvents[1], allEvents: previewEvents) } #if os(iOS) .navigationViewStyle(.stack) #endif ExampleView(model: .init(state: .init(name: "Hello"))) .debugSheet() #if os(iOS) .navigationViewStyle(.stack) #endif } } }
yonaskolb/SwiftComponent
16
Where architecture meets tooling
Swift
yonaskolb
Yonas Kolb
Sources/SwiftComponent/UI/ComponentListView.swift
Swift
import SwiftUI import SwiftPreview public struct ComponentListView: View { @Environment(\.colorScheme) var colorScheme: ColorScheme var components: [any Component.Type] let scale = 0.5 let device = Device.mediumPhone var environments: [String] @State var testRuns: [String: ItemTestRun] = [:] @State var selectedSnapshotTag: String? @State var snapshotTags: Set<String> = [] @AppStorage("componentList.viewType") var viewType: ViewType = .grid @AppStorage("componentList.environmentGroups") var environmentGroups: Bool = true var showEnvironmentGroups: Bool { environments.count > 1 && environmentGroups } enum ViewType: String, CaseIterable { case grid case list case snapshots var label: String { switch self { case .grid: return "Grid" case .list: return "List" case .snapshots: return "Snapshots" } } } struct ItemTestRun { let component: any Component.Type var environment: String let passed: Int let failed: Int let total: Int let snapshots: [SnapshotViewModel] } @MainActor struct ComponentViewModel: Identifiable { var id: String var component: any Component.Type var view: AnyView init<ComponentType: Component>(component: ComponentType.Type) { self.id = ComponentType.Model.baseName self.component = component self.view = AnyView(ComponentType.view(model: ComponentType.previewModel())) } } struct SnapshotViewModel: Identifiable { let componentType: any Component.Type var component: String { String(describing: componentType) } let snapshot: String let environment: String let view: AnyView let tags: Set<String> var id: String { "\(component).\(snapshot)"} } public init(components: [any Component.Type], selectedSnapshotTag: String? = nil) { self.components = components self._selectedSnapshotTag = .init(initialValue: selectedSnapshotTag) let environments = components.map { $0.environmentName } self.environments = Set(environments).sorted { if $0 == String(describing: EmptyEnvironment.self) { return true } else if $1 == String(describing: EmptyEnvironment.self) { return false } else { return $0 < $1 } } } func snapshotModels(environment: String? = nil) -> [SnapshotViewModel] { testRuns .sorted { $0.key < $1.key } .map(\.value) .filter { environment == nil || $0.environment == environment } .reduce([]) { $0 + $1.snapshots } .filter { if let selectedSnapshotTag { $0.tags.contains(selectedSnapshotTag) } else { true } } } var componentModels: [ComponentViewModel] { var models: [ComponentViewModel] = [] for component in components { models.append(ComponentViewModel(component: component)) } return models } func componentModels(environment: String) -> [ComponentViewModel] { componentModels.filter { $0.component.environmentName == environment } } func runTests() { Task { @MainActor in for environment in environments { for component in components { await test(component, environment: environment) } } } } func test<C: Component>(_ component: C.Type, environment: String) async { guard String(describing: C.environmentName) == environment else { return } var testRun = TestRun<C>() var snapshots: [ComponentSnapshot<C.Model>] = [] for test in C.tests { let result = await C.run(test) for stepResult in result.steps { testRun.addStepResult(stepResult, test: test) } testRun.completeTest(test, result: result) snapshots.append(contentsOf: result.snapshots) snapshotTags.formUnion(result.snapshots.reduce([]) { $0 + $1.tags}) } let itemTestRun = ItemTestRun( component: component, environment: C.environmentName, passed: testRun.passedStepCount, failed: testRun.failedStepCount, total: testRun.totalStepCount, snapshots: snapshots .map { .init( componentType: component, snapshot: $0.name, environment: C.environmentName, view: AnyView(C.view(model: $0.viewModel())), tags: $0.tags ) } ) testRuns[C.Model.baseName] = itemTestRun } public var body: some View { NavigationView { VStack { header content } #if os(iOS) .navigationViewStyle(.stack) #endif .background(colorScheme == .dark ? Color.darkBackground : .white) } #if os(iOS) .navigationViewStyle(.stack) #endif .largePreview() .task { runTests() } } var header: some View { HStack(spacing: 20) { Picker("View", selection: $viewType.animation()) { ForEach(ViewType.allCases, id: \.rawValue) { viewType in Text(viewType.label) .tag(viewType) } } .pickerStyle(.segmented) .fixedSize() .padding(.vertical, 2) // to give space for snapshot picker Spacer() if viewType == .snapshots, !snapshotTags.isEmpty { HStack(spacing: 0) { Text("Tags") .font(.callout) Picker("Tags", selection: $selectedSnapshotTag.animation()) { Text("All") .tag(Optional<String>.none) ForEach(snapshotTags.sorted(), id: \.self) { tag in Text(tag) .tag(tag as String?) } } .pickerStyle(.menu) .labelsHidden() } } if environments.count > 1 { HStack { Text("Environment") .font(.callout) Toggle(isOn: $environmentGroups.animation()) { Text("Environments") } .fixedSize() .labelsHidden() } } } .padding(.horizontal, 20) .padding(.vertical, 12) } var content: some View { ScrollView { switch viewType { case .grid: LazyVGrid(columns: [.init(.adaptive(minimum: device.width * scale + 20))], spacing: 0) { if showEnvironmentGroups { ForEach(environments, id: \.self) { environment in Section(header: environmentHeader(environment)) { gridItemViews(componentModels(environment: environment)) } } } else { gridItemViews(componentModels) } } case .list: LazyVStack { if showEnvironmentGroups { ForEach(environments, id: \.self) { environment in Section(header: environmentHeader(environment)) { listItemViews(componentModels(environment: environment)) } } } else { listItemViews(componentModels) } } case .snapshots: LazyVGrid(columns: [.init(.adaptive(minimum: device.width * scale + 20))], spacing: 0) { if showEnvironmentGroups { ForEach(environments, id: \.self) { environment in Section(header: environmentHeader(environment)) { snapsotItemViews(snapshotModels(environment: environment)) } } } else { snapsotItemViews(snapshotModels()) } } } } } @ViewBuilder func environmentHeader(_ environment: String) -> some View { if environments.count > 1 { Text(environment) .bold() .frame(maxWidth: .infinity, alignment: .leading) .font(.system(size: 20)) .padding(.horizontal, 26) .padding(.vertical, 12) .padding(.top, 20) } else { EmptyView() } } func gridItemViews(_ componentModels: [ComponentViewModel]) -> some View { ForEach(componentModels) { component in AnyView(gridItemView(component.component, model: component)) } } func listItemViews(_ componentModels: [ComponentViewModel]) -> some View { ForEach(componentModels) { component in Divider() AnyView(listItemView(component.component)) } } func snapsotItemViews(_ snapshotModels: [SnapshotViewModel]) -> some View { ForEach(snapshotModels) { snapshot in AnyView(snapshotView(snapshot: snapshot, component: snapshot.componentType)) } } func gridItemView<ComponentType: Component>( _ component: ComponentType.Type, model: ComponentViewModel) -> some View { NavigationLink { ComponentPreview<ComponentType>() } label: { VStack(spacing: 4) { model.view .embedIn(device: device) .previewColorScheme() .previewReference() .allowsHitTesting(false) .scaleEffect(scale) .frame(width: device.width*scale, height: device.height*scale) .padding(.bottom, 16) Text(ComponentType.Model.baseName) .bold() .font(.system(size: 20)) testResults(component) Spacer() } .interactiveBackground() .padding(20) } .buttonStyle(.plain) } func snapshotView<ComponentType: Component>(snapshot: SnapshotViewModel, component: ComponentType.Type) -> some View { NavigationLink { ComponentPreview<ComponentType>() } label: { VStack(spacing: 4) { snapshot.view .embedIn(device: device) .previewColorScheme() .previewReference() .allowsHitTesting(false) .scaleEffect(scale) .frame(width: device.width*scale, height: device.height*scale) .padding(.bottom, 16) Text(ComponentType.Model.baseName) .bold() .font(.system(size: 20)) Text(snapshot.snapshot) .foregroundColor(.secondary) .font(.system(size: 20)) } .interactiveBackground() .padding(20) } .buttonStyle(.plain) } func listItemView<ComponentType: Component>( _ component: ComponentType.Type) -> some View { NavigationLink { ComponentPreview<ComponentType>() } label: { HStack { Text(ComponentType.Model.baseName) .font(.system(size: 18)) Spacer() if ComponentType.environmentName != String(describing: EmptyEnvironment.self) { Text(ComponentType.environmentName) .foregroundColor(.secondary) } testResults(component) .frame(minWidth: 100) } .padding() .padding(.horizontal) .interactiveBackground() } .buttonStyle(.plain) } @ViewBuilder func testResults<ComponentType: Component>(_ component: ComponentType.Type) -> some View { if let testRun = testRuns[ComponentType.Model.baseName] { HStack(spacing: 4) { if testRun.failed > 0 { Text(testRun.failed.description) .bold() .padding(.horizontal, 10) .padding(.vertical, 2) .background { Capsule().fill(Color.red) } .foregroundColor(.white) } if testRun.passed > 0 { Text(testRun.passed.description) .bold() .padding(.horizontal, 10) .padding(.vertical, 2) .background { Capsule().fill(Color.green) } .foregroundColor(.white) } } } } } extension Component { static var id: String { Model.baseName } } struct ComponentTypeListView_Previews: PreviewProvider { static var previews: some View { ComponentListView(components: [ExampleComponent.self, ExampleComponent.self, ExampleComponent.self, ExampleComponent.self, ExampleComponent.self]) } }
yonaskolb/SwiftComponent
16
Where architecture meets tooling
Swift
yonaskolb
Yonas Kolb
Sources/SwiftComponent/UI/ComponentPreview.swift
Swift
import SwiftUI import SwiftPreview struct ComponentPreview<ComponentType: Component>: View { @StateObject var model = ComponentType.previewModel().logEvents() @AppStorage("componentPreview.viewState") var viewState: ViewState = .dashboard enum ViewState: String, CaseIterable { case dashboard = "Component" case view = "View" case model = "Model" case code = "Code" case tests = "Tests" } var body: some View { VStack(spacing: 0) { Divider() .padding(.top) Group { switch viewState { case .dashboard: ComponentDashboardView<ComponentType>(model: model) case .view: ComponentViewPreview(content: ComponentType.view(model: model)) case .tests: ComponentTestsView<ComponentType>() case .code: ComponentEditorView<ComponentType>() case .model: ComponentDescriptionView<ComponentType>() } } .toolbar { ToolbarItem(placement: .principal) { Picker(selection: $viewState) { ForEach(ViewState.allCases, id: \.rawValue) { viewState in Text(viewState.rawValue).tag(viewState) } } label: { Text("Mode") } // .scaleEffect(1.5) .pickerStyle(.segmented) .fixedSize() } } #if os(iOS) .navigationViewStyle(.stack) .navigationBarTitleDisplayMode(.inline) #endif .largePreview() } // .edgesIgnoringSafeArea(.all) } } struct ComponentPreviewView_Previews: PreviewProvider { static var previews: some View { NavigationView { ComponentPreview<ExampleComponent>() } #if os(iOS) .navigationViewStyle(.stack) #endif .largePreview() } }
yonaskolb/SwiftComponent
16
Where architecture meets tooling
Swift
yonaskolb
Yonas Kolb
Sources/SwiftComponent/UI/ComponentSnapshotView.swift
Swift
// // SwiftUIView.swift // // // Created by Yonas Kolb on 26/6/2023. // import SwiftUI @MainActor struct ComponentSnapshotView<ComponentType: Component>: View { let snapshotName: String @State var snapshot: ComponentSnapshot<ComponentType.Model>? func generateSnapshot() async { if let snapshot = ComponentType.snapshots.first(where: { $0.name == snapshotName}) { self.snapshot = snapshot return } for test in ComponentType.tests { let model = ViewModel<ComponentType.Model>(state: test.state, environment: test.environment) let result = await ComponentType.runTest(test, model: model, assertions: [], delay: 0, sendEvents: false) for snapshot in result.snapshots { if snapshot.name == snapshotName { self.snapshot = snapshot return } } } } var body: some View { ZStack { if let snapshot { ComponentType.view(model: snapshot.viewModel()) } else { ProgressView() .task { await generateSnapshot() } } } } } struct ComponentSnapshotView_Previews: PreviewProvider { static var previews: some View { ComponentSnapshotView<ExampleComponent>(snapshotName: "tapped") } }
yonaskolb/SwiftComponent
16
Where architecture meets tooling
Swift
yonaskolb
Yonas Kolb
Sources/SwiftComponent/UI/ComponentTestsView.swift
Swift
import Foundation import SwiftUI struct ComponentTestsView<ComponentType: Component>: View { typealias Model = ComponentType.Model @State var testRun = TestRun<ComponentType>() @AppStorage("testPreview.showStepTitles") var showStepTitles = true @AppStorage("testPreview.showEvents") var showEvents = false @AppStorage("testPreview.showMutations") var showMutations = false @AppStorage("testPreview.showDependencies") var showDependencies = false @AppStorage("testPreview.showExpectations") var showExpectations = false @AppStorage("testPreview.showErrors") var showErrors = true @AppStorage("testPreview.showWarnings") var showWarnings = false @AppStorage("testPreview.showErrorDiffs") var showErrorDiffs = true @AppStorage("testPreview.testFilter") var testFilter: TestFilter? @State var collapsedTests: [String: Bool] = [:] @State var showViewOptions = false @State var testResults: [TestStepResult] = [] @State var errorDiffVisibility: [UUID: Bool] = [:] @State var scrollToStep: UUID? @State var fixing: [UUID: Bool] = [:] var verticalSpacing = 10.0 var diffAddedColor: Color = .green var diffRemovedColor: Color = .red var diffErrorExpectedColor: Color = .green var diffErrorRecievedColor: Color = .red var diffWarningRecievedColor: Color = .orange typealias CollapsedTests = [String: [String: Bool]] enum TestFilter: String { case passed case failed case warnings } func barColor(_ result: TestStepResult) -> Color { if result.success { if showWarnings || testFilter == .warnings, !result.assertionWarnings.isEmpty { return Color.orange } else { return Color.green } } else { return Color.red } } func toggleErrorDiffVisibility(_ id: UUID) { withAnimation { errorDiffVisibility[id] = !showErrorDiff(id) } } func showErrorDiff(_ id: UUID) -> Bool { errorDiffVisibility[id] ?? showErrorDiffs } func getCollapsedTests() -> [String: Bool] { let collapsedTests = UserDefaults.standard.value(forKey: "testPreview.collapsedTests") as? CollapsedTests ?? [:] return collapsedTests[ComponentType.Model.baseName] ?? [:] } func testIsCollapsed(_ test: Test<ComponentType>) -> Bool { collapsedTests[test.testName] ?? false } func collapseTest(_ test: Test<ComponentType>, _ collapsed: Bool) { withAnimation { collapsedTests[test.testName] = collapsed } var collapsedAllTests = UserDefaults.standard.value(forKey: "testPreview.collapsedTests") as? CollapsedTests ?? [:] collapsedAllTests[ComponentType.Model.baseName, default: [:]][test.testName] = collapsed UserDefaults.standard.setValue(collapsedAllTests, forKey: "testPreview.collapsedTests") } func collapseAll() { let allCollapsed = ComponentType.tests.reduce(true) { $0 && testIsCollapsed($1) } ComponentType.tests.forEach { collapseTest($0, !allCollapsed) } } func runAllTests() { collapsedTests = getCollapsedTests() Task { @MainActor in print("\nRunning \(ComponentType.tests.count) Tests for \(Model.baseName)") testRun.reset(ComponentType.tests) for test in ComponentType.tests { await runTest(test) } withAnimation { testRun.checkCoverage() } let passed = testRun.testState.values.filter { $0.passed }.count let failed = testRun.testState.values.filter { !$0.passed }.count var string = "\n\(failed == 0 ? "✅" : "🛑") \(Model.baseName) Tests: \(passed) passed" if failed > 0 { string += ", \(failed) failed" } print(string) } } @MainActor func runTest(_ test: Test<ComponentType>) async { testRun.startTest(test) let model = ViewModel<Model>(state: test.state, environment: test.environment) let result = await ComponentType.runTest(test, model: model, assertions: ComponentType.testAssertions, delay: 0, sendEvents: false) { result in testRun.addStepResult(result, test: test) DispatchQueue.main.async { // withAnimation { testResults = testRun.getTestResults(for: ComponentType.tests) // } } } testRun.completeTest(test, result: result) var string = "" let indent = " " let newline = "\n" string += result.success ? "✅" : "🛑" string += " \(Model.baseName): \(test.testName)" for step in result.steps { for error in step.allErrors { string += newline + indent + error.error if let diff = error.diff { string += ":" + newline + indent + diff.joined(separator: newline + indent) } } } print(string) } func setFilter(_ filter: TestFilter?) { withAnimation { if testFilter != nil, self.testFilter == filter { self.testFilter = nil } else { self.testFilter = filter } } } func showTest(_ test: Test<ComponentType>) -> Bool { switch testFilter { case .none: return true case .warnings: return (testRun.testState[test.id]?.warningCount ?? 0) > 0 case .passed: return testRun.testState[test.id]?.passed ?? false case .failed: return testRun.testState[test.id]?.failed ?? false } } func tap(_ result: TestStepResult) { scrollToStep = result.id } func fix(error: TestError, with fixit: String) { // read file guard let data = FileManager.default.contents(atPath: error.source.file.description) else { return } guard var sourceFile = String(data: data, encoding: .utf8) else { return } fixing[error.id] = true var lines = sourceFile.split(separator: "\n", omittingEmptySubsequences: false).map(String.init) let line = Int(error.source.line) // edit file guard line > 0, line < lines.count - 1 else { return } let currentLine = lines[line - 1] guard let currentIndentIndex = currentLine.firstIndex(where: { !$0.isWhitespace }) else { return } let indent = String(currentLine[..<currentIndentIndex]) // TODO: check actual indent lines.insert(indent + " " + fixit, at: line) sourceFile = lines.joined(separator: "\n") // write file ComponentType.writeSource(sourceFile) } var body: some View { VStack(alignment: .leading, spacing: 0) { header resultBar coverage Divider() ScrollView { ScrollViewReader { scrollProxy in LazyVStack(spacing: 20) { ForEach(ComponentType.tests, id: \.id) { test in if showTest(test) { testRow(test) .background(Color(white: 1)) .cornerRadius(12) .overlay { RoundedRectangle(cornerRadius: 12).stroke(Color(white: 0.8)) } // .shadow(color: Color(white: 0, opacity: 0.1), radius: 6) } } } .onChange(of: scrollToStep) { step in if let step { withAnimation { scrollProxy.scrollTo(step, anchor: .top) } } } } .padding(20) } .background(Color(white: 0.9)) .animation(.default, value: showStepTitles) .animation(.default, value: showDependencies) .animation(.default, value: showEvents) .animation(.default, value: showMutations) .animation(.default, value: showExpectations) .animation(.default, value: showErrors) .animation(.default, value: showErrorDiffs) .animation(.default, value: showWarnings) .animation(.default, value: testFilter) } .task { runAllTests() } } @ViewBuilder func filterButton(_ filter: TestFilter?, color: Color, label: String, count: Int) -> some View { let selected = testFilter == filter Button(action: { setFilter(filter) }) { HStack { Text(count.description) .fontWeight(.bold) .foregroundColor(.white) .fixedSize() .monospacedDigit() Text(label) .foregroundColor(.white) .fontWeight(.bold) } .font(.title2) .padding(.vertical, 7) .padding(.horizontal, 12) .background { RoundedRectangle(cornerRadius: 6).fill(count == 0 ? Color.gray : color) } .padding(3) .overlay { if selected { RoundedRectangle(cornerRadius: 9).stroke(.primary, lineWidth: 3) } } } .buttonStyle(.plain) } var header: some View { VStack(alignment: .leading) { HStack(alignment: .bottom, spacing: 20) { // filterButton(.none, color: Color(white: 0.4), label: "All Tests", count: ComponentType.tests.count) filterButton(.passed, color: .green, label: "Passed", count: testRun.passedTestCount) filterButton(.failed, color: .red, label: "Failed", count: testRun.failedTestCount) filterButton(.warnings, color: .orange, label: "Improvements", count: testRun.stepWarningsCount) Spacer() HStack(spacing: 30) { Button(action: { showViewOptions = true }) { Text("Settings") .foregroundColor(.secondary) } .buttonStyle(.plain) .popover(isPresented: $showViewOptions) { VStack(alignment: .trailing, spacing: 12) { // TODO: add tasks Toggle("Show step titles", isOn: $showStepTitles) Toggle("Show dependencies", isOn: showStepTitles ? $showDependencies : .constant(false)) .disabled(!showStepTitles) Toggle("Show events", isOn: $showEvents) Toggle("Show mutation diffs", isOn: $showMutations) Toggle("Show expectations", isOn: $showExpectations.animation()) Toggle("Show assertion warnings", isOn: testFilter == .warnings ? .constant(true) : $showWarnings) .disabled(testFilter == .warnings) Toggle("Show errors", isOn: $showErrors) Toggle("Show error diffs", isOn: showErrors ? $showErrorDiffs : .constant(false)) .disabled(!showErrors) } .padding(24) } Button(action: collapseAll) { Text("Collapse") .foregroundColor(.secondary) } .buttonStyle(.plain) } .font(.headline) .padding(.trailing, 16) } } .padding() } var resultBar: some View { HStack(spacing: 2) { ForEach(testResults, id: \.id) { result in Button(action: { tap(result) }) { barColor(result) } } } .frame(height: 12) .cornerRadius(6) .clipped() .padding(.horizontal) .padding(.bottom) } @ViewBuilder var coverage: some View { if testRun.missingCoverage.hasValues { ScrollView(.horizontal) { HStack { ForEach(testRun.missingCoverage.actions.sorted(), id: \.self) { coverageBadge(type: "Action", name: $0) } ForEach(testRun.missingCoverage.routes.sorted(), id: \.self) { coverageBadge(type: "Route", name: $0) } ForEach(testRun.missingCoverage.outputs.sorted(), id: \.self) { coverageBadge(type: "Output", name: $0) } } .padding() } } } func coverageBadge(type: String, name: String) -> some View { Text("\(type).\(name)") .foregroundColor(.white) .padding(8) .background(Color.orange) .cornerRadius(6) } func testRow(_ test: Test<ComponentType>) -> some View { VStack(alignment: .leading, spacing: 0) { testHeader(test) .padding(16) .background(Color(white: 0.98)) if !testIsCollapsed(test) { Divider() .padding(.bottom, 8) if let steps = testRun.testResults[test.id] { VStack(alignment: .leading, spacing: 0) { ForEach(steps, id: \.self) { step in if let stepResult = testRun.testStepResults[step], showDependencies || stepResult.title != "Dependency" { stepResultRow(stepResult, test: test) .id(step) } } } .padding(.horizontal, 16) .padding(.bottom, 20) } } } } func testHeader(_ test: Test<ComponentType>) -> some View { Button { collapseTest(test, !testIsCollapsed(test)) // Task { @MainActor in // await runTest(test) // } } label: { let testResult = testRun.getTestState(test) HStack { HStack(spacing: 8) { ZStack { switch testResult { case .running: Image(systemName: "circle") case .complete(let result): if result.success { Image(systemName: "checkmark.circle.fill").foregroundColor(.green) } else { Image(systemName: "exclamationmark.octagon.fill").foregroundColor(.red) } case .notRun: Image(systemName: "circle") case .pending: Image(systemName: "play.circle").foregroundColor(.gray) case .failedToRun: Image(systemName: "x.circle.fill").foregroundColor(.red) } } .foregroundColor(testResult.color) Text(test.testName) .bold() .foregroundColor(testResult.color) } .font(.title3) Spacer() switch testResult { case .complete(let result): Text(result.formattedDuration) .font(.body) .foregroundColor(.secondary) .padding(.horizontal) default: EmptyView() } // if !runningTests { // Image(systemName: "play.circle") // .font(.title3) // } collapseIcon(collapsed: testIsCollapsed(test)) .foregroundColor(.secondary) } .contentShape(Rectangle()) // .animation(nil) } .buttonStyle(.plain) } func collapseIcon(collapsed: Bool) -> some View { ZStack { Image(systemName: "chevron.right") .opacity(collapsed ? 1 : 0) Image(systemName: "chevron.down") .opacity(!collapsed ? 1 : 0) } } func stepColor(stepResult: TestStepResult, test: Test<ComponentType>) -> Color { switch testRun.getTestState(test) { case .complete(let result): if result.success { return .green } else { return stepResult.success ? .secondary : .red } default: return .secondary } } func stepResultRow(_ stepResult: TestStepResult, test: Test<ComponentType>) -> some View { HStack(alignment: .top, spacing: 0) { if showStepTitles { HStack { // Group { // if stepResult.success { // Image(systemName: "checkmark.circle.fill") // } else { // Image(systemName: "x.circle.fill") // } // } bullet .padding(4) .foregroundColor(stepColor(stepResult: stepResult, test: test)) .padding(.trailing, 4) .padding(.top, verticalSpacing) } } VStack(alignment: .leading, spacing: 0) { // groups are to fix a rare compiler type inference error HStack { if showStepTitles { HStack(spacing: 0) { Text(stepResult.title) .bold() if let details = stepResult.details { Text(": " + details) } } .lineLimit(1) // .foregroundColor(stepColor(stepResult: stepResult, test: test)) .foregroundColor(.testContent) .padding(.top, verticalSpacing) } if showDependencies { Spacer() HStack { ForEach(stepResult.coverage.dependencies.sorted(), id: \.self) { dependency in Text(dependency) .padding(.vertical, 3) .padding(.horizontal, 6) .foregroundColor(.white) .background(Color.gray) .cornerRadius(6) } } } } Group { if showEvents, !stepResult.events.isEmpty { stepEvents(stepResult.events) .padding(.top, verticalSpacing) } } Group { if !showEvents, showMutations, !stepResult.mutations.isEmpty { stepMutations(stepResult.mutations) .padding(.top, verticalSpacing) } } Group { if !stepResult.children.isEmpty { VStack(alignment: .leading, spacing: 0) { ForEach(stepResult.children, id: \.id) { result in // AnyView fixes compiler error AnyView(self.stepResultRow(result, test: test)) } } } } Group { if showExpectations, !stepResult.expectations.isEmpty { stepExpectations(stepResult.expectations) .padding(.top, verticalSpacing) } } Group { if showErrors, !stepResult.errors.isEmpty { stepResultErrors(stepResult.errors) .padding(.top, verticalSpacing) } } Group { if showWarnings || testFilter == .warnings, !stepResult.assertionWarnings.isEmpty { stepResultErrors(stepResult.assertionWarnings, warning: true) .padding(.top, verticalSpacing) } } } } } func stepEvents(_ events: [Event]) -> some View { VStack(alignment: .leading, spacing:8) { ForEach(events.sorted { $0.start < $1.start }) { event in VStack(alignment: .leading) { NavigationLink { ComponentEventView(event: event, allEvents: events) } label: { HStack { // Text(event.type.emoji) Text("Event: ") + Text(event.type.title).bold() + Text(" " + event.type.details) Spacer() Text(event.path.droppingRoot?.string ?? "") .foregroundColor(.secondary) } } switch event.type { case .mutation(let mutation): if showMutations { mutationView(mutation) } default: EmptyView() } } .foregroundColor(.testContent) } } } func stepMutations(_ mutations: [Mutation]) -> some View { VStack(alignment: .leading, spacing:8) { ForEach(mutations, id: \.id) { mutation in mutationView(mutation) } } } @ViewBuilder func mutationView(_ mutation: Mutation) -> some View { if let diff = mutation.stateDiff { VStack(alignment: .leading) { diff .diffText(removedColor: diffRemovedColor, addedColor: diffAddedColor) .frame(maxWidth: .infinity, alignment: .leading) } .textContainer() .cornerRadius(8) .padding(.bottom, 8) } } func stepExpectations(_ expectations: [String]) -> some View { VStack(alignment: .leading, spacing:8) { ForEach(expectations, id: \.self) { expectation in HStack { Text(expectation) } .foregroundColor(.testContent) } } } func stepResultErrors(_ errors: [TestError], warning: Bool = false) -> some View { VStack(alignment: .leading, spacing: 12) { ForEach(errors, id: \.id) { error in VStack(alignment: .leading, spacing: 0) { Button(action: { toggleErrorDiffVisibility(error.id) }) { HStack { Image(systemName: warning ? "exclamationmark.triangle.fill" : "exclamationmark.octagon.fill") Text(error.error) .bold() .padding(.vertical, 10) Spacer() if let fixit = error.fixit, fixing[error.id] != true { Button(action: { fix(error: error, with: fixit) }) { Text("Fix") .bold() .padding(-2) } .buttonStyle(.bordered) } if error.diff != nil { collapseIcon(collapsed: !showErrorDiff(error.id)) } } .foregroundColor(.white) .padding(.horizontal, 12) .background { warning ? Color.orange : Color.red } .contentShape(Rectangle()) // .shadow(radius: 10) } .buttonStyle(.plain) if showErrorDiffs, showErrorDiff(error.id), let diff = error.diff { // Divider() diff .diffText(removedColor: warning ? diffWarningRecievedColor : diffErrorRecievedColor, addedColor: diffErrorExpectedColor) .frame(maxWidth: .infinity, alignment: .leading) .textContainer() } } .cornerRadius(8) .clipped() } } } var bullet: some View { Circle().frame(width: 12, height: 12) } } extension Color { static let testContent: Color = Color(white: 0.4) } extension View { func textContainer() -> some View { self .padding(.vertical, 12) .padding(.horizontal, 8) .background(Color(white: 0.15)) } } extension [String] { private func getTextLine(_ line: String, textColor: Color, removedColor: Color, addedColor: Color, multiline: Bool) -> Text { var line = String(line) var color = textColor var change: Bool = false if line.hasPrefix("+") { line = " " + String(line.dropFirst(1)) color = addedColor change = true } else if line.hasPrefix("-") { line = " " + String(line.dropFirst(1)) color = removedColor change = true } let parts = line.split(separator: ":") let text: Text let recolorPropertyNames = false if recolorPropertyNames, parts.count > 1, multiline { let property = Text(parts[0] + ":") // .foregroundColor(color) .foregroundColor(color.opacity(0.5)) // .foregroundColor(textColor) // .bold() let rest = Text(parts.dropFirst().joined(separator: ":")) .foregroundColor(color) text = property + rest } else { text = Text(line) .foregroundColor(color) } if change { // text = text.bold() } return text } func diffText(textColor: Color = Color(white: 0.8), removedColor: Color = .red, addedColor: Color = .green) -> some View { var text = Text("") let lines = self for (index, line) in lines.enumerated() { var line = line if index != lines.count - 1 { line += "\n" } text = text + getTextLine(line, textColor: textColor, removedColor: removedColor, addedColor: addedColor, multiline: lines.count > 2) } return text.fixedSize(horizontal: false, vertical: true) } } struct ComponentTests_Previews: PreviewProvider { static var previews: some View { NavigationView { ComponentTestsView<ExampleComponent>() } #if os(iOS) .navigationViewStyle(.stack) #endif .largePreview() } }
yonaskolb/SwiftComponent
16
Where architecture meets tooling
Swift
yonaskolb
Yonas Kolb
Sources/SwiftComponent/UI/ComponentViewPreview.swift
Swift
import Foundation import SwiftUI import SwiftPreview struct ComponentViewPreview<Content: View>: View { var sizeCategories: [ContentSizeCategory] = [ .extraSmall, .large, .extraExtraExtraLarge, .accessibilityExtraExtraExtraLarge, ] var devices: [Device] = Device.all @State var sizeCategory: ContentSizeCategory = .large @State var buttonScale: CGFloat = 0.20 @State var device = Device.iPhone14 @State var showDevicePicker = false @State var showAccessibilityPreview = false @AppStorage("componentPreview.viewMode") var viewMode: ViewMode = .phone @AppStorage("componentPreview.deviceScale") var deviceScale: Scaling = Scaling.fit @AppStorage("componentPreview.showEnvironmentSelector") var showEnvironmentSelector = false enum ViewMode: String { case device case fill case fit case phone } @Environment(\.colorScheme) var systemColorScheme: ColorScheme let content: Content let name: String? public init(content: Content, name: String? = nil) { self.content = content self.name = name } var body: some View { GeometryReader { proxy in VStack(spacing: 0) { VStack(spacing: 0) { if let name { Text(name) .bold() .font(.title2) .padding(.bottom) } if showAccessibilityPreview { #if os(iOS) content.accessibilityPreview() #else contentView #endif } else { switch viewMode { case .device: ScalingView(size: device.frameSize, scaling: deviceScale) { contentView .embedIn(device: device) .previewColorScheme() .shadow(radius: 10) } case .phone: ScalingView(size: Device.mediumPhone.frameSize, scaling: .fit) { contentView .embedIn(device: .phone) .previewColorScheme() .shadow(radius: 10) } case .fill: contentView .frame(maxWidth: .infinity, maxHeight: .infinity) .background(.background) .previewColorScheme() case .fit: contentView .background(.background) .previewColorScheme() .cornerRadius(12) .clipped() .shadow(radius: 4) .padding(16) .frame(maxHeight: .infinity) } } } configBar(previewHeight: min(200, proxy.size.height/5)) } .animation(.default, value: showEnvironmentSelector) .animation(.default, value: viewMode) } #if os(iOS) .navigationViewStyle(StackNavigationViewStyle()) #endif } var contentView: some View { content .environment(\.sizeCategory, sizeCategory) .previewColorScheme() } var environmentPreview: some View { content .allowsHitTesting(false) .previewReference() } func configBar(previewHeight: CGFloat) -> some View { VStack(alignment: .leading, spacing: 0) { Divider() Group { if #available(iOS 16.0, macOS 13.0, *) { ViewThatFits(in: .horizontal) { HStack(spacing: 8) { viewModeSelector .fixedSize() deviceControls Spacer() environmentToggle .frame(width: 200) } VStack(alignment: .leading) { HStack(spacing: 8) { viewModeSelector .fixedSize() Spacer() environmentToggle } if viewMode == .device { deviceControls } } VStack(alignment: .leading) { viewModeSelector if viewMode == .device { deviceControls } environmentToggle } } } else { VStack(alignment: .leading) { HStack(spacing: 12) { viewModeSelector Spacer() environmentToggle } if viewMode == .device { deviceControls } } } } .foregroundColor(.primary) .padding(.top) .padding(.horizontal) .buttonStyle(.plain) if showEnvironmentSelector { ScrollView(.horizontal) { HStack(spacing: 40) { colorSchemeSelector(height: previewHeight) sizeCategorySelector(height: previewHeight) } .padding(.top) .padding(.horizontal, 20) } .transition(.move(edge: .bottom)) } } .background(systemColorScheme == .dark ? Color(white: 0.05) : Color(white: 0.95)) } var environmentToggle: some View { Button(action: { showEnvironmentSelector.toggle() }) { Text("Environment") Image(systemName: "chevron.down") } .font(.subheadline) .buttonStyle(.bordered) .transformEffect(.identity) // fixes postion during animation https://stackoverflow.com/questions/70253645/swiftui-animate-view-transition-and-position-change-at-the-same-time/76094274#76094274 } var viewModeSelector: some View { Picker(selection: $viewMode) { Text("Phone") .tag(ViewMode.phone) Text("Device") .tag(ViewMode.device) Text("Fill") .tag(ViewMode.fill) Text("Fit") .tag(ViewMode.fit) } label: { EmptyView() } .pickerStyle(.segmented) } var deviceControls: some View { HStack(spacing: 12) { Button { showDevicePicker = true } label: { HStack { device.icon Text(device.name) } .font(.subheadline) } .buttonStyle(.bordered) .fixedSize() .popover(isPresented: $showDevicePicker) { deviceSelector .padding(20) } .disabled(viewMode != .device) .opacity(viewMode == .device ? 1 : 0) Picker(selection: $deviceScale) { Text("100%") .tag(Scaling.exact) Text("Fit") .tag(Scaling.fit) } label: { EmptyView() } .pickerStyle(.segmented) .fixedSize() .disabled(viewMode != .device) .opacity(viewMode == .device ? 1 : 0) } } func sizeCategorySelector(height: CGFloat) -> some View { HStack(spacing: 12) { ForEach(sizeCategories, id: \.self) { size in Button(action: { withAnimation { sizeCategory = size } }) { VStack(spacing: 8) { Text(size.acronym) .bold() .lineLimit(1) environmentPreview .environment(\.sizeCategory, size) .embedIn(device: device) .previewColorScheme() .scaleEffect(height / device.frameSize.height) .frame(height: height) Image(systemName: size == sizeCategory ? "checkmark.circle.fill" : "circle") .font(.system(size: 20)) } .frame(width: device.frameSize.width * (height / device.frameSize.height)) } .buttonStyle(.plain) } } } func colorSchemeSelector(height: CGFloat) -> some View { HStack(spacing: 12) { ForEach(ColorScheme.allCases, id: \.self) { colorScheme in Button { if PreviewColorScheme.current.colorScheme == colorScheme { PreviewColorScheme.current = .system } else { PreviewColorScheme.current = .init(colorScheme: colorScheme) } } label: { VStack(spacing: 8) { Text(colorScheme == .light ? "Light" : (colorScheme == .dark ? "Dark" : "Automatic")) .bold() environmentPreview .environment(\.sizeCategory, sizeCategory) .embedIn(device: device) .colorScheme(colorScheme) .scaleEffect(height / device.frameSize.height) .frame(height: height) Image(systemName: PreviewColorScheme.current.colorScheme == colorScheme ? "checkmark.circle.fill" : "circle") .font(.system(size: 20)) } .frame(width: device.frameSize.width * (height / device.frameSize.height)) } .buttonStyle(.plain) } } } var deviceSelector: some View { VStack(spacing: 40) { HStack { ForEach(Device.iPhones, id: \.name, content: deviceView) } HStack { ForEach(Device.iPads, id: \.name, content: deviceView) } } .foregroundColor(.accentColor) } func deviceView(_ device: Device) -> some View { Button { withAnimation { self.device = device self.viewMode = .device } } label: { VStack(spacing: 2) { device.icon .font(.system(size: 100, weight: .ultraLight)) //.scaleEffect(device.scale * device.contentScale, anchor: .bottom) var nameParts = device.name.components(separatedBy: " ") let deviceType = nameParts.removeFirst() let name = "\(deviceType)\n\(nameParts.joined(separator: " "))" Text(name) .bold() .font(.footnote) .multilineTextAlignment(.center) Image(systemName: self.device == device ? "checkmark.circle.fill" : "circle") .font(.system(size: 30)) .padding(.top, 2) } } .buttonStyle(.plain) } } extension View { public func preview(name: String? = nil) -> some View { ComponentViewPreview(content: self, name: name) } } extension ContentSizeCategory { var acronym: String { switch self { case .extraSmall: return "XS" case .small: return "S" case .medium: return "M" case .large: return "L" case .extraLarge: return "XL" case .extraExtraLarge: return "XXL" case .extraExtraExtraLarge: return "XXXL" case .accessibilityMedium: return "AM" case .accessibilityLarge: return "AL" case .accessibilityExtraLarge: return "AXL" case .accessibilityExtraExtraLarge: return "AXXL" case .accessibilityExtraExtraExtraLarge: return "AXXXL" @unknown default: return "" } } } struct ViewPreviewer_Previews: PreviewProvider { static var previews: some View { // NavigationView { VStack { Text("🌻") .font(.system(size: 100)) Text("Hello, world") .font(.title2) } .navigationTitle(Text("My App")) .toolbar { ToolbarItem(placement: .navigation) { Image(systemName: "plus") } } // } .preview() .largePreview() } }
yonaskolb/SwiftComponent
16
Where architecture meets tooling
Swift
yonaskolb
Yonas Kolb
Sources/SwiftComponent/UI/PreviewColorScheme.swift
Swift
import Foundation import SwiftUI extension View { func previewColorScheme() -> some View { modifier(PreviewColorSchemeModifier()) } } struct PreviewColorSchemeModifier: ViewModifier { @AppStorage(PreviewColorScheme.key) var previewColorScheme: PreviewColorScheme = .system @Environment(\.colorScheme) var systemColorScheme: ColorScheme func body(content: Content) -> some View { content.colorScheme(previewColorScheme.colorScheme ?? systemColorScheme) } } enum PreviewColorScheme: String { case system case dark case light static let key = "componentPreview.colorScheme" @AppStorage(key) static var current: PreviewColorScheme = .system var colorScheme: ColorScheme? { switch self { case .system: return nil case .dark: return .dark case .light: return .light } } init(colorScheme: ColorScheme) { switch colorScheme { case .light: self = .light case .dark: self = .dark @unknown default: self = .system } } } extension Color { static let darkBackground = Color(white: 0.15) }
yonaskolb/SwiftComponent
16
Where architecture meets tooling
Swift
yonaskolb
Yonas Kolb
Sources/SwiftComponent/UI/PreviewDevice.swift
Swift
import Foundation import SwiftUI extension View { public func largePreview() -> some View { self.previewDevice(.iPad) } }
yonaskolb/SwiftComponent
16
Where architecture meets tooling
Swift
yonaskolb
Yonas Kolb
Sources/SwiftComponent/UI/PreviewReference.swift
Swift
import SwiftUI struct PreviewReferenceKey: EnvironmentKey { static var defaultValue: Bool = false } extension EnvironmentValues { public var isPreviewReference: Bool { get { self[PreviewReferenceKey.self] } set { self[PreviewReferenceKey.self] = newValue } } } struct ViewAppearanceTaskKey: EnvironmentKey { static var defaultValue: Bool = true } extension EnvironmentValues { public var viewAppearanceTask: Bool { get { self[ViewAppearanceTaskKey.self] } set { self[ViewAppearanceTaskKey.self] = newValue } } } extension View { /// disables component views from calling their appearance task public func previewReference() -> some View { self .environment(\.isPreviewReference, true) .environment(\.viewAppearanceTask, false) } }
yonaskolb/SwiftComponent
16
Where architecture meets tooling
Swift
yonaskolb
Yonas Kolb
Sources/SwiftComponent/ViewModel.swift
Swift
import Foundation import SwiftUI import Combine @dynamicMemberLookup @MainActor public class ViewModel<Model: ComponentModel>: ObservableObject { let store: ComponentStore<Model> public var path: ComponentPath { store.path } public var componentName: String { Model.baseName } private var cancellables: Set<AnyCancellable> = [] public var dependencies: ComponentDependencies { store.dependencies } public var environment: Model.Environment { store.environment } var children: [UUID: WeakRef] = [:] public internal(set) var state: Model.State { get { store.state } set { // update listeners in internal tools that can set the state directly store._$observationRegistrar.withMutation(of: store, keyPath: \.state) { store.state = newValue } } } public var route: Model.Route? { get { store.route } set { store.route = newValue } } public convenience init(state: Model.State, route: Model.Route? = nil) where Model.Environment == EmptyEnvironment { self.init(store: .init(state: .root(state), path: nil, graph: .init(), environment: EmptyEnvironment(), route: route)) } public convenience init(state: Binding<Model.State>, route: Model.Route? = nil) where Model.Environment == EmptyEnvironment { self.init(store: .init(state: .binding(.init(binding: state)), path: nil, graph: .init(), environment: EmptyEnvironment(), route: route)) } public convenience init(state: Model.State, environment: Model.Environment, route: Model.Route? = nil) { self.init(store: .init(state: .root(state), path: nil, graph: .init(), environment: environment, route: route)) } public convenience init(state: Binding<Model.State>, environment: Model.Environment, route: Model.Route? = nil) { self.init(store: .init(state: .binding(.init(binding: state)), path: nil, graph: .init(), environment: environment, route: route)) } init(store: ComponentStore<Model>) { self.store = store self.store.stateChanged.sink { [weak self] _ in DispatchQueue.main.async { self?.objectWillChange.send() } } .store(in: &cancellables) self.store.routeChanged.sink { [weak self] _ in self?.objectWillChange.send() } .store(in: &cancellables) self.store.environmentChanged.sink { [weak self] _ in self?.objectWillChange.send() } .store(in: &cancellables) store.graph.add(self) } deinit { // print("deinit ViewModel \(Model.baseName)") // TODO: update to isolated deinit in Swift 6.2 MainActor.assumeIsolated { store.graph.remove(self) } } public func onEvent(includeGrandchildren: Bool = true, _ event: @escaping (Event) -> Void) -> Self { store.onEvent(includeGrandchildren: includeGrandchildren, event) return self } public func logEvents(_ events: Set<EventSimpleType> = Set(EventSimpleType.allCases), childEvents: Bool = true) -> Self { store.logEvents.formUnion(events) store.logChildEvents = childEvents return self } public func sendViewBodyEvents(_ send: Bool = true) -> Self { self.store.graph.sendViewBodyEvents = send return self } /// access state public subscript<Value>(dynamicMember keyPath: KeyPath<Model.State, Value>) -> Value { store.state[keyPath: keyPath] } /// access getters directly on a model that can access things like state, environment or dependencies public subscript<Value>(dynamicMember keyPath: KeyPath<Model, Value>) -> Value { store.model[keyPath: keyPath] } @MainActor public func send(_ action: Model.Action, file: StaticString = #filePath, line: UInt = #line) { store.processAction(action, source: .capture(file: file, line: line)) } /// an async version of send. Can be used when you want to wait for the action to be handled, such as in a SwiftUI refreshable closure @MainActor // would like to use @_disfavoredOverload but doesn't seem to work when called from tests public func sendAsync(_ action: Model.Action, file: StaticString = #filePath, line: UInt = #line) async { await store.processAction(action, source: .capture(file: file, line: line)) } @MainActor public func binding<Value>(_ keyPath: WritableKeyPath<Model.State, Value>, file: StaticString = #filePath, line: UInt = #line) -> Binding<Value> { store.binding(keyPath, file: file, line: line) } @MainActor func appear(first: Bool, file: StaticString = #filePath, line: UInt = #line) { store.appear(first: first, file: file, line: line) } @MainActor func appearAsync(first: Bool, file: StaticString = #filePath, line: UInt = #line) async { await store.appear(first: first, file: file, line: line) } @MainActor func disappear(file: StaticString = #filePath, line: UInt = #line) { store.disappear(file: file, line: line) } @MainActor func disappearAsync(file: StaticString = #filePath, line: UInt = #line) async { await store.disappear(file: file, line: line) } @MainActor func bodyAccessed(start: Date, file: StaticString = #filePath, line: UInt = #line) { store.bodyAccessed(start: start, file: file, line: line) } } // MARK: Scoping extension ViewModel { // MARK: Different environment // state binding and output -> input public func scope<Child: ComponentModel>(stateBinding: Binding<Child.State>, environment: Child.Environment, output: @escaping (Child.Output) -> Model.Input) -> ViewModel<Child> { store.scope(state: .binding(stateBinding), environment: environment, output: .input(output)).viewModel() } // state binding and output -> output public func scope<Child: ComponentModel>(stateBinding: Binding<Child.State>, environment: Child.Environment, output: @escaping (Child.Output) -> Model.Output) -> ViewModel<Child> { store.scope(state: .binding(stateBinding), environment: environment, output: .output(output)).viewModel() } // state binding and output -> Never public func scope<Child: ComponentModel>(stateBinding: Binding<Child.State>, environment: Child.Environment) -> ViewModel<Child> where Child.Output == Never { store.scope(state: .binding(stateBinding), environment: environment).viewModel() } // statePath and output -> input public func scope<Child: ComponentModel>(state: WritableKeyPath<Model.State, Child.State>, environment: Child.Environment, output: @escaping (Child.Output) -> Model.Input) -> ViewModel<Child> { store.scope(state: .keyPath(state), environment: environment, output: .input(output)).viewModel() } // statePath and output -> output public func scope<Child: ComponentModel>(state: WritableKeyPath<Model.State, Child.State>, environment: Child.Environment, output: @escaping (Child.Output) -> Model.Output) -> ViewModel<Child> { store.scope(state: .keyPath(state), environment: environment, output: .output(output)).viewModel() } // optional statePath and output -> input public func scope<Child: ComponentModel>(state: WritableKeyPath<Model.State, Child.State?>, value: Child.State, environment: Child.Environment, output: @escaping (Child.Output) -> Model.Input) -> ViewModel<Child> { store.scope(state: .optionalKeyPath(state, fallback: value), environment: environment, output: .input(output)).viewModel() } // optional statePath, case and output -> input public func scope<Child: ComponentModel, Destination: CasePathable>(state: WritableKeyPath<Model.State, Destination?>, case: CaseKeyPath<Destination, Child.State>, value: Child.State, environment: Child.Environment, output: @escaping (Child.Output) -> Model.Input) -> ViewModel<Child> { store.scope(state: self.store.caseScopedState(state: state, case: `case`, value: value), environment: environment, output: .input(output)).viewModel() } // optional statePath and output -> output public func scope<Child: ComponentModel>(state: WritableKeyPath<Model.State, Child.State?>, value: Child.State, environment: Child.Environment, output: @escaping (Child.Output) -> Model.Output) -> ViewModel<Child> { store.scope(state: .optionalKeyPath(state, fallback: value), environment: environment, output: .output(output)).viewModel() } // optional statePath, case and output -> output public func scope<Child: ComponentModel, Destination: CasePathable>(state: WritableKeyPath<Model.State, Destination?>, case: CaseKeyPath<Destination, Child.State>, value: Child.State, environment: Child.Environment, output: @escaping (Child.Output) -> Model.Output) -> ViewModel<Child> { store.scope(state: self.store.caseScopedState(state: state, case: `case`, value: value), environment: environment, output: .output(output)).viewModel() } // optional statePath and output -> Never public func scope<Child: ComponentModel>(state: WritableKeyPath<Model.State, Child.State?>, value: Child.State, environment: Child.Environment) -> ViewModel<Child> where Child.Output == Never { store.scope(state: .optionalKeyPath(state, fallback: value), environment: environment).viewModel() } // optional statePath, case and output -> Never public func scope<Child: ComponentModel, Destination: CasePathable>(state: WritableKeyPath<Model.State, Destination?>, case: CaseKeyPath<Destination, Child.State>, value: Child.State, environment: Child.Environment) -> ViewModel<Child> where Child.Output == Never { store.scope(state: self.store.caseScopedState(state: state, case: `case`, value: value), environment: environment).viewModel() } // statePath and output -> Never public func scope<Child: ComponentModel>(state: WritableKeyPath<Model.State, Child.State>, environment: Child.Environment) -> ViewModel<Child> where Child.Output == Never { store.scope(state: .keyPath(state), environment: environment).viewModel() } // state and output -> Never public func scope<Child: ComponentModel>(state: Child.State, environment: Child.Environment) -> ViewModel<Child> where Child.Output == Never { store.scope(state: .value(state), environment: environment).viewModel() } // state and output -> input public func scope<Child: ComponentModel>(state: Child.State, environment: Child.Environment, output: @escaping (Child.Output) -> Model.Input) -> ViewModel<Child> { store.scope(state: .value(state), environment: environment, output: .input(output)).viewModel() } // state and output -> output public func scope<Child: ComponentModel>(state: Child.State, environment: Child.Environment, output: @escaping (Child.Output) -> Model.Output) -> ViewModel<Child> { store.scope(state: .value(state), environment: environment, output: .output(output)).viewModel() } // MARK: same environment // state binding and output -> input public func scope<Child: ComponentModel>(stateBinding: Binding<Child.State>, output: @escaping (Child.Output) -> Model.Input) -> ViewModel<Child> where Model.Environment == Child.Environment { store.scope(state: .binding(stateBinding), output: .input(output)).viewModel() } // state binding and output -> output public func scope<Child: ComponentModel>(stateBinding: Binding<Child.State>, output: @escaping (Child.Output) -> Model.Output) -> ViewModel<Child> where Model.Environment == Child.Environment { store.scope(state: .binding(stateBinding), output: .output(output)).viewModel() } // state binding and output -> Never public func scope<Child: ComponentModel>(stateBinding: Binding<Child.State>) -> ViewModel<Child> where Child.Output == Never, Model.Environment == Child.Environment { store.scope(state: .binding(stateBinding)).viewModel() } // statePath and output -> input public func scope<Child: ComponentModel>(state: WritableKeyPath<Model.State, Child.State>, output: @escaping (Child.Output) -> Model.Input) -> ViewModel<Child> where Model.Environment == Child.Environment { store.scope(state: .keyPath(state), output: .input(output)).viewModel() } // statePath and output -> output public func scope<Child: ComponentModel>(state: WritableKeyPath<Model.State, Child.State>, output: @escaping (Child.Output) -> Model.Output) -> ViewModel<Child> where Model.Environment == Child.Environment { store.scope(state: .keyPath(state), output: .output(output)).viewModel() } // optional statePath and output -> input public func scope<Child: ComponentModel>(state: WritableKeyPath<Model.State, Child.State?>, value: Child.State, output: @escaping (Child.Output) -> Model.Input) -> ViewModel<Child> where Model.Environment == Child.Environment { store.scope(state: .optionalKeyPath(state, fallback: value), output: .input(output)).viewModel() } // optional statePath, case and output -> input public func scope<Child: ComponentModel, Destination: CasePathable>(state: WritableKeyPath<Model.State, Destination?>, case: CaseKeyPath<Destination, Child.State>, value: Child.State, output: @escaping (Child.Output) -> Model.Input) -> ViewModel<Child> where Model.Environment == Child.Environment { store.scope(state: self.store.caseScopedState(state: state, case: `case`, value: value), output: .input(output)).viewModel() } // optional statePath and output -> output public func scope<Child: ComponentModel>(state: WritableKeyPath<Model.State, Child.State?>, value: Child.State, output: @escaping (Child.Output) -> Model.Output) -> ViewModel<Child> where Model.Environment == Child.Environment { store.scope(state: .optionalKeyPath(state, fallback: value), output: .output(output)).viewModel() } // optional statePath, case and output -> output public func scope<Child: ComponentModel, Destination: CasePathable>(state: WritableKeyPath<Model.State, Destination?>, case: CaseKeyPath<Destination, Child.State>, value: Child.State, output: @escaping (Child.Output) -> Model.Output) -> ViewModel<Child> where Model.Environment == Child.Environment { store.scope(state: self.store.caseScopedState(state: state, case: `case`, value: value), output: .output(output)).viewModel() } // optional statePath and output -> Never public func scope<Child: ComponentModel>(state: WritableKeyPath<Model.State, Child.State?>, value: Child.State) -> ViewModel<Child> where Child.Output == Never, Model.Environment == Child.Environment { store.scope(state: .optionalKeyPath(state, fallback: value)).viewModel() } // optional statePath, case and output -> Never public func scope<Child: ComponentModel, Destination: CasePathable>(state: WritableKeyPath<Model.State, Destination?>, case: CaseKeyPath<Destination, Child.State>, value: Child.State) -> ViewModel<Child> where Child.Output == Never, Model.Environment == Child.Environment { store.scope(state: self.store.caseScopedState(state: state, case: `case`, value: value)).viewModel() } // statePath and output -> Never public func scope<Child: ComponentModel>(state: WritableKeyPath<Model.State, Child.State>) -> ViewModel<Child> where Child.Output == Never, Model.Environment == Child.Environment { store.scope(state: .keyPath(state)).viewModel() } // state and output -> Never public func scope<Child: ComponentModel>(state: Child.State) -> ViewModel<Child> where Child.Output == Never, Model.Environment == Child.Environment { store.scope(state: .value(state)).viewModel() } // state and output -> input public func scope<Child: ComponentModel>(state: Child.State, output: @escaping (Child.Output) -> Model.Input) -> ViewModel<Child> where Model.Environment == Child.Environment { store.scope(state: .value(state), output: .input(output)).viewModel() } // state and output -> output public func scope<Child: ComponentModel>(state: Child.State, output: @escaping (Child.Output) -> Model.Output) -> ViewModel<Child> where Model.Environment == Child.Environment { store.scope(state: .value(state), output: .output(output)).viewModel() } public func scope<Child: ComponentModel>(_ connection: ComponentConnection<Model, Child>) -> ViewModel<Child> { return connection.convert(self) } } extension ViewModel: Identifiable { public var id: UUID { store.id } } extension ComponentStore { func viewModel() -> ViewModel<Model> { .init(store: self) } }
yonaskolb/SwiftComponent
16
Where architecture meets tooling
Swift
yonaskolb
Yonas Kolb
Sources/SwiftComponentCLI/CLI.swift
Swift
import Foundation import ArgumentParser @main struct Components: ParsableCommand { static var configuration = CommandConfiguration( abstract: "A tool for SwiftComponent", subcommands: [ GenerateComponents.self, ]) }
yonaskolb/SwiftComponent
16
Where architecture meets tooling
Swift
yonaskolb
Yonas Kolb
Sources/SwiftComponentCLI/GenerateComponents.swift
Swift
import Foundation import SwiftParser import SwiftSyntax import ArgumentParser struct GenerateComponents: ParsableCommand { static var configuration = CommandConfiguration( commandName: "generate-components", abstract: "Generates a file containing all the Components in the directory" ) @Argument var directory: String @Argument var outputFile: String mutating func run() throws { let files = try FileManager.default.subpathsOfDirectory(atPath: directory) var componentList: [String] = [] for file in files { if file.hasSuffix(".swift") { let filePath = "\(directory)/\(file)" if let contents = FileManager.default.contents(atPath: filePath), let source = String(data: contents, encoding: .utf8) { // TODO: enable better parsing. It's slow right now compared to regex // let syntax = Parser.parse(source: source) // if let component = syntax.getStruct(type: "Component") { // componentList.append(component.name.text) // } if #available(macOS 13.0, iOS 16.0, *) { let regex = #/(struct|extension) (?<component>.*):.*Component[, ]/# if let match = try regex.firstMatch(in: source) { componentList.append(String(match.output.component)) } } } } } componentList.sort() print("Found \(componentList.count) Components in \(directory):") print(componentList.joined(separator: "\n")) let file = """ import SwiftComponent #if DEBUG public let components: [any Component.Type] = [ \(componentList.map { "\($0).self" }.joined(separator: ",\n ")) ] #else public let components: [any Component.Type] = [] #endif """ let data = file.data(using: .utf8)! do { try data.write(to: URL(fileURLWithPath: outputFile)) } catch { print(error) } } } extension SyntaxProtocol { func getStruct(type: String) -> StructDeclSyntax? { getChild { structSyntax in guard let typeClause: InheritedTypeListSyntax = structSyntax.getChild(), let _ = typeClause.getChild(compare: { $0.name.text == type }) as IdentifierTypeSyntax? else { return false } return true } } func getChild<ChildType: SyntaxProtocol>(compare: (ChildType) -> Bool = { _ in true }) -> ChildType? { for child in children(viewMode: .sourceAccurate) { if let structSyntax = child.as(ChildType.self), compare(structSyntax) { return structSyntax } else if let childState = child.getChild(compare: compare) { return childState } } return nil } }
yonaskolb/SwiftComponent
16
Where architecture meets tooling
Swift
yonaskolb
Yonas Kolb
Sources/SwiftComponentMacros/Availability.swift
Swift
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2023 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // //===----------------------------------------------------------------------===// import SwiftDiagnostics import SwiftOperators import SwiftSyntax import SwiftSyntaxBuilder import SwiftSyntaxMacros extension AttributeSyntax { var availability: AttributeSyntax? { if attributeName.identifier == "available" { return self } else { return nil } } } extension IfConfigClauseSyntax.Elements { var availability: IfConfigClauseSyntax.Elements? { switch self { case .attributes(let attributes): if let availability = attributes.availability { return .attributes(availability) } else { return nil } default: return nil } } } extension IfConfigClauseSyntax { var availability: IfConfigClauseSyntax? { if let availability = elements?.availability { return with(\.elements, availability) } else { return nil } } var clonedAsIf: IfConfigClauseSyntax { detached.with(\.poundKeyword, .poundIfToken()) } } extension IfConfigDeclSyntax { var availability: IfConfigDeclSyntax? { var elements = [IfConfigClauseListSyntax.Element]() for clause in clauses { if let availability = clause.availability { if elements.isEmpty { elements.append(availability.clonedAsIf) } else { elements.append(availability) } } } if elements.isEmpty { return nil } else { return with(\.clauses, IfConfigClauseListSyntax(elements)) } } } extension AttributeListSyntax.Element { var availability: AttributeListSyntax.Element? { switch self { case .attribute(let attribute): if let availability = attribute.availability { return .attribute(availability) } case .ifConfigDecl(let ifConfig): if let availability = ifConfig.availability { return .ifConfigDecl(availability) } } return nil } } extension AttributeListSyntax { var availability: AttributeListSyntax? { var elements = [AttributeListSyntax.Element]() for element in self { if let availability = element.availability { elements.append(availability) } } if elements.isEmpty { return nil } return AttributeListSyntax(elements) } }
yonaskolb/SwiftComponent
16
Where architecture meets tooling
Swift
yonaskolb
Yonas Kolb
Sources/SwiftComponentMacros/Extensions.swift
Swift
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2023 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // //===----------------------------------------------------------------------===// import SwiftDiagnostics import SwiftOperators import SwiftSyntax import SwiftSyntaxBuilder import SwiftSyntaxMacros extension VariableDeclSyntax { var identifierPattern: IdentifierPatternSyntax? { bindings.first?.pattern.as(IdentifierPatternSyntax.self) } var isInstance: Bool { for modifier in modifiers { for token in modifier.tokens(viewMode: .all) { if token.tokenKind == .keyword(.static) || token.tokenKind == .keyword(.class) { return false } } } return true } var identifier: TokenSyntax? { identifierPattern?.identifier } var type: TypeSyntax? { bindings.first?.typeAnnotation?.type } func accessorsMatching(_ predicate: (TokenKind) -> Bool) -> [AccessorDeclSyntax] { let patternBindings = bindings.compactMap { binding in binding.as(PatternBindingSyntax.self) } let accessors: [AccessorDeclListSyntax.Element] = patternBindings.compactMap { patternBinding in switch patternBinding.accessorBlock?.accessors { case .accessors(let accessors): return accessors default: return nil } }.flatMap { $0 } return accessors.compactMap { accessor in guard let decl = accessor.as(AccessorDeclSyntax.self) else { return nil } if predicate(decl.accessorSpecifier.tokenKind) { return decl } else { return nil } } } var willSetAccessors: [AccessorDeclSyntax] { accessorsMatching { $0 == .keyword(.willSet) } } var didSetAccessors: [AccessorDeclSyntax] { accessorsMatching { $0 == .keyword(.didSet) } } var isComputed: Bool { if accessorsMatching({ $0 == .keyword(.get) }).count > 0 { return true } else { return bindings.contains { binding in if case .getter = binding.accessorBlock?.accessors { return true } else { return false } } } } var isImmutable: Bool { return bindingSpecifier.tokenKind == .keyword(.let) } func isEquivalent(to other: VariableDeclSyntax) -> Bool { if isInstance != other.isInstance { return false } return identifier?.text == other.identifier?.text } var initializer: InitializerClauseSyntax? { bindings.first?.initializer } func hasMacroApplication(_ name: String) -> Bool { for attribute in attributes { switch attribute { case .attribute(let attr): if attr.attributeName.tokens(viewMode: .all).map({ $0.tokenKind }) == [.identifier(name)] { return true } default: break } } return false } func firstAttribute(for name: String) -> AttributeSyntax? { for attribute in attributes { switch attribute { case .attribute(let attr): if attr.attributeName.tokens(viewMode: .all).map({ $0.tokenKind }) == [.identifier(name)] { return attr } default: break } } return nil } } extension TypeSyntax { var identifier: String? { for token in tokens(viewMode: .all) { switch token.tokenKind { case .identifier(let identifier): return identifier default: break } } return nil } func genericSubstitution(_ parameters: GenericParameterListSyntax?) -> String? { var genericParameters = [String: TypeSyntax?]() if let parameters { for parameter in parameters { genericParameters[parameter.name.text] = parameter.inheritedType } } var iterator = self.asProtocol(TypeSyntaxProtocol.self).tokens(viewMode: .sourceAccurate) .makeIterator() guard let base = iterator.next() else { return nil } if let genericBase = genericParameters[base.text] { if let text = genericBase?.identifier { return "some " + text } else { return nil } } var substituted = base.text while let token = iterator.next() { switch token.tokenKind { case .leftAngle: substituted += "<" case .rightAngle: substituted += ">" case .comma: substituted += "," case .identifier(let identifier): let type: TypeSyntax = "\(raw: identifier)" guard let substituedType = type.genericSubstitution(parameters) else { return nil } substituted += substituedType break default: // ignore? break } } return substituted } } extension FunctionDeclSyntax { var isInstance: Bool { for modifier in modifiers { for token in modifier.tokens(viewMode: .all) { if token.tokenKind == .keyword(.static) || token.tokenKind == .keyword(.class) { return false } } } return true } struct SignatureStandin: Equatable { var isInstance: Bool var identifier: String var parameters: [String] var returnType: String } var signatureStandin: SignatureStandin { var parameters = [String]() for parameter in signature.parameterClause.parameters { parameters.append( parameter.firstName.text + ":" + (parameter.type.genericSubstitution(genericParameterClause?.parameters) ?? "")) } let returnType = signature.returnClause?.type.genericSubstitution(genericParameterClause?.parameters) ?? "Void" return SignatureStandin( isInstance: isInstance, identifier: name.text, parameters: parameters, returnType: returnType) } func isEquivalent(to other: FunctionDeclSyntax) -> Bool { return signatureStandin == other.signatureStandin } } extension DeclGroupSyntax { var memberFunctionStandins: [FunctionDeclSyntax.SignatureStandin] { var standins = [FunctionDeclSyntax.SignatureStandin]() for member in memberBlock.members { if let function = member.as(MemberBlockItemSyntax.self)?.decl.as(FunctionDeclSyntax.self) { standins.append(function.signatureStandin) } } return standins } func hasMemberFunction(equvalentTo other: FunctionDeclSyntax) -> Bool { for member in memberBlock.members { if let function = member.as(MemberBlockItemSyntax.self)?.decl.as(FunctionDeclSyntax.self) { if function.isEquivalent(to: other) { return true } } } return false } func hasMemberProperty(equivalentTo other: VariableDeclSyntax) -> Bool { for member in memberBlock.members { if let variable = member.as(MemberBlockItemSyntax.self)?.decl.as(VariableDeclSyntax.self) { if variable.isEquivalent(to: other) { return true } } } return false } var definedVariables: [VariableDeclSyntax] { memberBlock.members.compactMap { member in if let variableDecl = member.as(MemberBlockItemSyntax.self)?.decl.as(VariableDeclSyntax.self) { return variableDecl } return nil } } func addIfNeeded(_ decl: DeclSyntax?, to declarations: inout [DeclSyntax]) { guard let decl else { return } if let fn = decl.as(FunctionDeclSyntax.self) { if !hasMemberFunction(equvalentTo: fn) { declarations.append(decl) } } else if let property = decl.as(VariableDeclSyntax.self) { if !hasMemberProperty(equivalentTo: property) { declarations.append(decl) } } } var isClass: Bool { return self.is(ClassDeclSyntax.self) } var isActor: Bool { return self.is(ActorDeclSyntax.self) } var isEnum: Bool { return self.is(EnumDeclSyntax.self) } var isStruct: Bool { return self.is(StructDeclSyntax.self) } }
yonaskolb/SwiftComponent
16
Where architecture meets tooling
Swift
yonaskolb
Yonas Kolb
Sources/SwiftComponentMacros/Macros.swift
Swift
import Foundation import SwiftCompilerPlugin import SwiftSyntaxMacros @main struct MyMacroPlugin: CompilerPlugin { let providingMacros: [Macro.Type] = [ ComponentModelMacro.self, ObservableStateMacro.self, ObservationStateTrackedMacro.self, ObservationStateIgnoredMacro.self, ResourceMacro.self ] }
yonaskolb/SwiftComponent
16
Where architecture meets tooling
Swift
yonaskolb
Yonas Kolb
Sources/SwiftComponentMacros/ModelMacro.swift
Swift
import Foundation import SwiftSyntaxMacros import SwiftSyntax public struct ComponentModelMacro {} extension ComponentModelMacro: MemberMacro { public static func expansion( of node: AttributeSyntax, providingMembersOf declaration: some DeclGroupSyntax, in context: some MacroExpansionContext ) throws -> [DeclSyntax] { guard declaration.isStruct else { throw MacroError.onlyStruct } // TODO: only make public if type is public return [ "public let _$context: Context", "public let _$connections: Connections = Self.Connections()", """ public init(context: Context) { self._$context = context } """, ] } } extension ComponentModelMacro: ExtensionMacro { public static func expansion( of node: AttributeSyntax, attachedTo declaration: some SwiftSyntax.DeclGroupSyntax, providingExtensionsOf type: some SwiftSyntax.TypeSyntaxProtocol, conformingTo protocols: [SwiftSyntax.TypeSyntax], in context: some SwiftSyntaxMacros.MacroExpansionContext ) throws -> [ExtensionDeclSyntax] { let declSyntax: DeclSyntax = """ extension \(type.trimmed): ComponentModel { } """ guard let extensionDecl = declSyntax.as(ExtensionDeclSyntax.self) else { return [] } return [extensionDecl] } } // TODO: replace this when a macro can add @MainActor to the whole type extension ComponentModelMacro: MemberAttributeMacro { public static func expansion( of node: AttributeSyntax, attachedTo declaration: some DeclGroupSyntax, providingAttributesFor member: some DeclSyntaxProtocol, in context: some MacroExpansionContext ) throws -> [AttributeSyntax] { if let syntax = member.as(FunctionDeclSyntax.self), !syntax.attributes.hasAttribute("MainActor") { return ["@MainActor"] } if let syntax = member.as(VariableDeclSyntax.self), !syntax.attributes.hasAttribute("MainActor") { return ["@MainActor"] } // if let syntax = member.as(StructDeclSyntax.self), // syntax.name.text == "Connections", // !syntax.attributes.hasAttribute("MainActor"){ // return ["@MainActor"] // } // add ObservableState to State if let syntax = member.as(StructDeclSyntax.self), syntax.name.text == "State", !syntax.attributes.hasAttribute("ObservableState"){ return ["@ObservableState"] } // add ObservableState and CasePathable to Destination if let syntax = member.as(EnumDeclSyntax.self), syntax.name.text == "Destination" { var attributes: [AttributeSyntax] = [] if !syntax.attributes.hasAttribute("ObservableState") { attributes.append("@ObservableState") } if !syntax.attributes.hasAttribute("CasePathable") { attributes.append("@CasePathable") } return attributes } return [] } } extension AttributeListSyntax { func hasAttribute(_ attribute: String) -> Bool { self.compactMap { $0.as(AttributeSyntax.self) }.contains { return $0.attributeName.description == attribute } } } enum MacroError: CustomStringConvertible, Error { case onlyStruct var description: String { switch self { case .onlyStruct: return "Can only be applied to a structure" } } }
yonaskolb/SwiftComponent
16
Where architecture meets tooling
Swift
yonaskolb
Yonas Kolb
Sources/SwiftComponentMacros/ObservableStateMacro.swift
Swift
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2023 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // //===----------------------------------------------------------------------===// import SwiftDiagnostics import SwiftOperators import SwiftSyntax import SwiftSyntaxBuilder import SwiftSyntaxMacros #if !canImport(SwiftSyntax600) import SwiftSyntaxMacroExpansion #endif public struct ObservableStateMacro { static let moduleName = "SwiftComponent" static let conformanceName = "ObservableState" static var qualifiedConformanceName: String { return "\(moduleName).\(conformanceName)" } static let originalConformanceName = "Observable" static var qualifiedOriginalConformanceName: String { "Observation.\(originalConformanceName)" } static var observableConformanceType: TypeSyntax { "\(raw: qualifiedConformanceName)" } static let registrarTypeName = "ObservationStateRegistrar" static var qualifiedRegistrarTypeName: String { "\(moduleName).\(registrarTypeName)" } static let idName = "ObservableStateID" static var qualifiedIDName: String { "\(moduleName).\(idName)" } static let trackedMacroName = "ObservationStateTracked" static let ignoredMacroName = "ObservationStateIgnored" static let registrarVariableName = "_$observationRegistrar" static func registrarVariable(_ observableType: TokenSyntax) -> DeclSyntax { return """ @\(raw: ignoredMacroName) var \(raw: registrarVariableName) = \(raw: qualifiedRegistrarTypeName)() """ } static func idVariable() -> DeclSyntax { return """ public var _$id: \(raw: qualifiedIDName) { \(raw: registrarVariableName).id } """ } static func willModifyFunction() -> DeclSyntax { return """ public mutating func _$willModify() { \(raw: registrarVariableName)._$willModify() } """ } static var ignoredAttribute: AttributeSyntax { AttributeSyntax( leadingTrivia: .space, atSign: .atSignToken(), attributeName: IdentifierTypeSyntax(name: .identifier(ignoredMacroName)), trailingTrivia: .space ) } } struct ObservationDiagnostic: DiagnosticMessage { enum ID: String { case invalidApplication = "invalid type" case missingInitializer = "missing initializer" } var message: String var diagnosticID: MessageID var severity: DiagnosticSeverity init( message: String, diagnosticID: SwiftDiagnostics.MessageID, severity: SwiftDiagnostics.DiagnosticSeverity = .error ) { self.message = message self.diagnosticID = diagnosticID self.severity = severity } init( message: String, domain: String, id: ID, severity: SwiftDiagnostics.DiagnosticSeverity = .error ) { self.message = message self.diagnosticID = MessageID(domain: domain, id: id.rawValue) self.severity = severity } } extension DiagnosticsError { init<S: SyntaxProtocol>( syntax: S, message: String, domain: String = "Observation", id: ObservationDiagnostic.ID, severity: SwiftDiagnostics.DiagnosticSeverity = .error ) { self.init(diagnostics: [ Diagnostic( node: Syntax(syntax), message: ObservationDiagnostic(message: message, domain: domain, id: id, severity: severity) ) ]) } } extension DeclModifierListSyntax { func privatePrefixed(_ prefix: String) -> DeclModifierListSyntax { let modifier: DeclModifierSyntax = DeclModifierSyntax(name: "private", trailingTrivia: .space) return [modifier] + filter { switch $0.name.tokenKind { case .keyword(let keyword): switch keyword { case .fileprivate, .private, .internal, .public, .package: return false default: return true } default: return true } } } init(keyword: Keyword) { self.init([DeclModifierSyntax(name: .keyword(keyword))]) } } extension TokenSyntax { func privatePrefixed(_ prefix: String) -> TokenSyntax { switch tokenKind { case .identifier(let identifier): return TokenSyntax( .identifier(prefix + identifier), leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia, presence: presence) default: return self } } } extension PatternBindingListSyntax { func privatePrefixed(_ prefix: String) -> PatternBindingListSyntax { var bindings = self.map { $0 } for index in 0..<bindings.count { let binding = bindings[index] if let identifier = binding.pattern.as(IdentifierPatternSyntax.self) { bindings[index] = PatternBindingSyntax( leadingTrivia: binding.leadingTrivia, pattern: IdentifierPatternSyntax( leadingTrivia: identifier.leadingTrivia, identifier: identifier.identifier.privatePrefixed(prefix), trailingTrivia: identifier.trailingTrivia ), typeAnnotation: binding.typeAnnotation, initializer: binding.initializer, accessorBlock: binding.accessorBlock, trailingComma: binding.trailingComma, trailingTrivia: binding.trailingTrivia) } } return PatternBindingListSyntax(bindings) } } extension VariableDeclSyntax { func privatePrefixed(_ prefix: String, addingAttribute attribute: AttributeSyntax) -> VariableDeclSyntax { let newAttributes = attributes + [.attribute(attribute)] return VariableDeclSyntax( leadingTrivia: leadingTrivia, attributes: newAttributes, modifiers: modifiers.privatePrefixed(prefix), bindingSpecifier: TokenSyntax( bindingSpecifier.tokenKind, leadingTrivia: .space, trailingTrivia: .space, presence: .present), bindings: bindings.privatePrefixed(prefix), trailingTrivia: trailingTrivia ) } var isValidForObservation: Bool { !isComputed && isInstance && !isImmutable && identifier != nil } } extension ObservableStateMacro: MemberMacro { public static func expansion< Declaration: DeclGroupSyntax, Context: MacroExpansionContext >( of node: AttributeSyntax, providingMembersOf declaration: Declaration, in context: Context ) throws -> [DeclSyntax] { guard !declaration.isEnum else { return try enumExpansion(of: node, providingMembersOf: declaration, in: context) } guard let identified = declaration.asProtocol(NamedDeclSyntax.self) else { return [] } let observableType = identified.name.trimmed if declaration.isClass { // classes are not supported throw DiagnosticsError( syntax: node, message: "'@ObservableState' cannot be applied to class type '\(observableType.text)'", id: .invalidApplication) } if declaration.isActor { // actors cannot yet be supported for their isolation throw DiagnosticsError( syntax: node, message: "'@ObservableState' cannot be applied to actor type '\(observableType.text)'", id: .invalidApplication) } var declarations = [DeclSyntax]() declaration.addIfNeeded( ObservableStateMacro.registrarVariable(observableType), to: &declarations) declaration.addIfNeeded(ObservableStateMacro.idVariable(), to: &declarations) declaration.addIfNeeded(ObservableStateMacro.willModifyFunction(), to: &declarations) return declarations } } extension [ObservableStateCase] { init(members: MemberBlockItemListSyntax) { var tag = 0 self.init(members: members, tag: &tag) } init(members: MemberBlockItemListSyntax, tag: inout Int) { self = members.flatMap { member -> [ObservableStateCase] in if let enumCaseDecl = member.decl.as(EnumCaseDeclSyntax.self) { return enumCaseDecl.elements.map { defer { tag += 1 } return ObservableStateCase.element($0, tag: tag) } } if let ifConfigDecl = member.decl.as(IfConfigDeclSyntax.self) { let configs = ifConfigDecl.clauses.flatMap { decl -> [ObservableStateCase.IfConfig] in guard let elements = decl.elements?.as(MemberBlockItemListSyntax.self) else { return [] } return [ ObservableStateCase.IfConfig( poundKeyword: decl.poundKeyword, condition: decl.condition, cases: Array(members: elements, tag: &tag) ) ] } return [.ifConfig(configs)] } return [] } } } enum ObservableStateCase { case element(EnumCaseElementSyntax, tag: Int) indirect case ifConfig([IfConfig]) struct IfConfig { let poundKeyword: TokenSyntax let condition: ExprSyntax? let cases: [ObservableStateCase] } var getCase: String { switch self { case let .element(element, tag): if let parameters = element.parameterClause?.parameters, parameters.count == 1 { return """ case let .\(element.name.text)(state): return ._$id(for: state)._$tag(\(tag)) """ } else { return """ case .\(element.name.text): return ObservableStateID()._$tag(\(tag)) """ } case let .ifConfig(configs): return configs .map { """ \($0.poundKeyword.text) \($0.condition?.trimmedDescription ?? "") \($0.cases.map(\.getCase).joined(separator: "\n")) """ } .joined(separator: "\n") + "#endif\n" } } var willModifyCase: String { switch self { case let .element(element, _): if let parameters = element.parameterClause?.parameters, parameters.count == 1, let parameter = parameters.first { return """ case var .\(element.name.text)(state): \(ObservableStateMacro.moduleName)._$willModify(&state) self = .\(element.name.text)(\(parameter.firstName.map { "\($0): " } ?? "")state) """ } else { return """ case .\(element.name.text): break """ } case let .ifConfig(configs): return configs .map { """ \($0.poundKeyword.text) \($0.condition?.trimmedDescription ?? "") \($0.cases.map(\.willModifyCase).joined(separator: "\n")) """ } .joined(separator: "\n") + "#endif\n" } } } extension ObservableStateMacro { public static func enumExpansion< Declaration: DeclGroupSyntax, Context: MacroExpansionContext >( of node: AttributeSyntax, providingMembersOf declaration: Declaration, in context: Context ) throws -> [DeclSyntax] { let cases = [ObservableStateCase](members: declaration.memberBlock.members) var getCases: [String] = [] var willModifyCases: [String] = [] for enumCase in cases { getCases.append(enumCase.getCase) willModifyCases.append(enumCase.willModifyCase) } return [ """ public var _$id: \(raw: qualifiedIDName) { switch self { \(raw: getCases.joined(separator: "\n")) } } """, """ public mutating func _$willModify() { switch self { \(raw: willModifyCases.joined(separator: "\n")) } } """, ] } } extension SyntaxStringInterpolation { // It would be nice for SwiftSyntaxBuilder to provide this out-of-the-box. mutating func appendInterpolation<Node: SyntaxProtocol>(_ node: Node?) { if let node { appendInterpolation(node) } } } extension ObservableStateMacro: MemberAttributeMacro { public static func expansion< Declaration: DeclGroupSyntax, MemberDeclaration: DeclSyntaxProtocol, Context: MacroExpansionContext >( of node: AttributeSyntax, attachedTo declaration: Declaration, providingAttributesFor member: MemberDeclaration, in context: Context ) throws -> [AttributeSyntax] { guard let property = member.as(VariableDeclSyntax.self), property.isValidForObservation, property.identifier != nil else { return [] } // dont apply to ignored properties or properties that are already flagged as tracked if property.hasMacroApplication(ObservableStateMacro.ignoredMacroName) || property.hasMacroApplication(ObservableStateMacro.trackedMacroName) { return [] } if !property.attributes.isEmpty { // if we're a property wrapper already ignore as that isn't compatible return [ AttributeSyntax( attributeName: IdentifierTypeSyntax( name: .identifier(ObservableStateMacro.ignoredMacroName))) ] } return [ AttributeSyntax( attributeName: IdentifierTypeSyntax( name: .identifier(ObservableStateMacro.trackedMacroName))) ] } } extension ObservableStateMacro: ExtensionMacro { public static func expansion( of node: AttributeSyntax, attachedTo declaration: some DeclGroupSyntax, providingExtensionsOf type: some TypeSyntaxProtocol, conformingTo protocols: [TypeSyntax], in context: some MacroExpansionContext ) throws -> [ExtensionDeclSyntax] { // This method can be called twice - first with an empty `protocols` when // no conformance is needed, and second with a `MissingTypeSyntax` instance. if protocols.isEmpty { return [] } return [ (""" \(declaration.attributes.availability)extension \(raw: type.trimmedDescription): \ \(raw: qualifiedConformanceName), Observation.Observable {} """ as DeclSyntax) .cast(ExtensionDeclSyntax.self) ] } } public struct ObservationStateTrackedMacro: AccessorMacro { public static func expansion< Context: MacroExpansionContext, Declaration: DeclSyntaxProtocol >( of node: AttributeSyntax, providingAccessorsOf declaration: Declaration, in context: Context ) throws -> [AccessorDeclSyntax] { guard let property = declaration.as(VariableDeclSyntax.self), property.isValidForObservation, let identifier = property.identifier?.trimmed else { return [] } if property.hasMacroApplication(ObservableStateMacro.ignoredMacroName) { return [] } let initAccessor: AccessorDeclSyntax = """ @storageRestrictions(initializes: _\(identifier)) init(initialValue) { _\(identifier) = initialValue } """ let getAccessor: AccessorDeclSyntax = """ get { \(raw: ObservableStateMacro.registrarVariableName).access(self, keyPath: \\.\(identifier)) return _\(identifier) } """ let setAccessor: AccessorDeclSyntax = """ set { \(raw: ObservableStateMacro.registrarVariableName).mutate(self, keyPath: \\.\(identifier), &_\(identifier), newValue, _$isIdentityEqual) } """ let modifyAccessor: AccessorDeclSyntax = """ _modify { let oldValue = _$observationRegistrar.willModify(self, keyPath: \\.\(identifier), &_\(identifier)) defer { _$observationRegistrar.didModify(self, keyPath: \\.\(identifier), &_\(identifier), oldValue, _$isIdentityEqual) } yield &_\(identifier) } """ return [initAccessor, getAccessor, setAccessor, modifyAccessor] } } extension ObservationStateTrackedMacro: PeerMacro { public static func expansion< Context: MacroExpansionContext, Declaration: DeclSyntaxProtocol >( of node: SwiftSyntax.AttributeSyntax, providingPeersOf declaration: Declaration, in context: Context ) throws -> [DeclSyntax] { guard let property = declaration.as(VariableDeclSyntax.self), property.isValidForObservation else { return [] } if property.hasMacroApplication(ObservableStateMacro.ignoredMacroName) || property.hasMacroApplication(ObservableStateMacro.trackedMacroName) { return [] } let storage = DeclSyntax( property.privatePrefixed("_", addingAttribute: ObservableStateMacro.ignoredAttribute)) return [storage] } } public struct ObservationStateIgnoredMacro: AccessorMacro { public static func expansion< Context: MacroExpansionContext, Declaration: DeclSyntaxProtocol >( of node: AttributeSyntax, providingAccessorsOf declaration: Declaration, in context: Context ) throws -> [AccessorDeclSyntax] { return [] } }
yonaskolb/SwiftComponent
16
Where architecture meets tooling
Swift
yonaskolb
Yonas Kolb
Sources/SwiftComponentMacros/ResourceMacro.swift
Swift
import SwiftDiagnostics import SwiftOperators import SwiftSyntax import SwiftSyntaxBuilder import SwiftSyntaxMacroExpansion import SwiftSyntaxMacros public enum ResourceMacro { } extension ResourceMacro: AccessorMacro { public static func expansion<D: DeclSyntaxProtocol, C: MacroExpansionContext>( of node: AttributeSyntax, providingAccessorsOf declaration: D, in context: C ) throws -> [AccessorDeclSyntax] { guard let property = declaration.as(VariableDeclSyntax.self), property.isValidForResource, let identifier = property.identifier?.trimmed else { return [] } let initAccessor: AccessorDeclSyntax = """ @storageRestrictions(initializes: _\(identifier)) init(initialValue) { _\(identifier) = ResourceState(wrappedValue: initialValue) } """ let getAccessor: AccessorDeclSyntax = """ get { _$observationRegistrar.access(self, keyPath: \\.\(identifier)) return _\(identifier).wrappedValue } """ let setAccessor: AccessorDeclSyntax = """ set { _$observationRegistrar.mutate(self, keyPath: \\.\(identifier), &_\(identifier).wrappedValue, newValue, _$isIdentityEqual) } """ // TODO: _modify accessor? return [initAccessor, getAccessor, setAccessor] } } extension ResourceMacro: PeerMacro { public static func expansion<D: DeclSyntaxProtocol, C: MacroExpansionContext>( of node: AttributeSyntax, providingPeersOf declaration: D, in context: C ) throws -> [DeclSyntax] { guard let property = declaration.as(VariableDeclSyntax.self), property.isValidForResource else { return [] } let wrapped = DeclSyntax( property.privateWrapped(addingAttribute: ObservableStateMacro.ignoredAttribute) ) let projected = DeclSyntax(property.projected) return [ projected, wrapped, ] } } extension VariableDeclSyntax { fileprivate func privateWrapped( addingAttribute attribute: AttributeSyntax ) -> VariableDeclSyntax { var attributes = self.attributes for index in attributes.indices.reversed() { let attribute = attributes[index] switch attribute { case let .attribute(attribute): if attribute.attributeName.tokens(viewMode: .all).map(\.tokenKind) == [ .identifier("Resource") ] { attributes.remove(at: index) } default: break } } let newAttributes = attributes + [.attribute(attribute)] return VariableDeclSyntax( leadingTrivia: leadingTrivia, attributes: newAttributes, modifiers: modifiers.privatePrefixed("_"), bindingSpecifier: TokenSyntax( bindingSpecifier.tokenKind, trailingTrivia: .space, presence: .present ), bindings: bindings.privateWrapped, trailingTrivia: trailingTrivia ) } fileprivate var projected: VariableDeclSyntax { VariableDeclSyntax( leadingTrivia: leadingTrivia, modifiers: modifiers, bindingSpecifier: TokenSyntax( bindingSpecifier.tokenKind, trailingTrivia: .space, presence: .present ), bindings: bindings.projected, trailingTrivia: trailingTrivia ) } fileprivate var isValidForResource: Bool { !isComputed && isInstance && !isImmutable && identifier != nil } } extension PatternBindingListSyntax { fileprivate var privateWrapped: PatternBindingListSyntax { var bindings = self for index in bindings.indices { var binding = bindings[index] if let optionalType = binding.typeAnnotation?.type.as(OptionalTypeSyntax.self) { binding.typeAnnotation = nil binding.initializer = InitializerClauseSyntax( value: FunctionCallExprSyntax( calledExpression: optionalType.wrappedType.resourceWrapped, leftParen: .leftParenToken(), arguments: [ LabeledExprSyntax( label: "wrappedValue", expression: binding.initializer?.value ?? ExprSyntax(NilLiteralExprSyntax()) ) ], rightParen: .rightParenToken() ) ) } if let identifier = binding.pattern.as(IdentifierPatternSyntax.self) { bindings[index] = PatternBindingSyntax( leadingTrivia: binding.leadingTrivia, pattern: IdentifierPatternSyntax( leadingTrivia: identifier.leadingTrivia, identifier: identifier.identifier.privatePrefixed("_"), trailingTrivia: identifier.trailingTrivia ), typeAnnotation: binding.typeAnnotation, initializer: binding.initializer, accessorBlock: binding.accessorBlock, trailingComma: binding.trailingComma, trailingTrivia: binding.trailingTrivia ) } } return bindings } fileprivate var projected: PatternBindingListSyntax { var bindings = self for index in bindings.indices { var binding = bindings[index] if let optionalType = binding.typeAnnotation?.type.as(OptionalTypeSyntax.self) { binding.typeAnnotation?.type = TypeSyntax( IdentifierTypeSyntax( name: .identifier(optionalType.wrappedType.resourceWrapped.trimmedDescription) ) ) } if let identifier = binding.pattern.as(IdentifierPatternSyntax.self) { bindings[index] = PatternBindingSyntax( leadingTrivia: binding.leadingTrivia, pattern: IdentifierPatternSyntax( leadingTrivia: identifier.leadingTrivia, identifier: identifier.identifier.privatePrefixed("$"), trailingTrivia: identifier.trailingTrivia ), typeAnnotation: binding.typeAnnotation, accessorBlock: AccessorBlockSyntax( accessors: .accessors([ """ get { _$observationRegistrar.access(self, keyPath: \\.\(identifier)) return _\(identifier.identifier).projectedValue } """, """ set { _$observationRegistrar.mutate(self, keyPath: \\.\(identifier), &_\(identifier).projectedValue, newValue, _$isIdentityEqual) } """, ]) ) ) } } return bindings } } extension TypeSyntax { fileprivate var resourceWrapped: GenericSpecializationExprSyntax { GenericSpecializationExprSyntax( expression: MemberAccessExprSyntax( base: DeclReferenceExprSyntax(baseName: "SwiftComponent"), name: "ResourceState" ), genericArgumentClause: GenericArgumentClauseSyntax( arguments: [ GenericArgumentSyntax( argument: self ) ] ) ) } }
yonaskolb/SwiftComponent
16
Where architecture meets tooling
Swift
yonaskolb
Yonas Kolb
Sources/SwiftPreview/Accessibility/AccessibilityHeirarchy.swift
Swift
#if os(iOS) import Foundation import SwiftUI import UIKit import AccessibilitySnapshotCore public typealias AccessibilityHierarchy = [AccessibilityMarker] extension View { public func accessibilityHierarchy(frame: CGRect = CGRect(origin: .zero, size: CGSize(width: 500, height: 2000))) -> AccessibilityHierarchy { self.renderView(in: frame) { view in view.accessibilityHierarchy() } } } extension UIView { func accessibilityHierarchy() -> AccessibilityHierarchy { let accessibilityHierarchyParser = AccessibilityHierarchyParser() return accessibilityHierarchyParser.parseAccessibilityElements(in: self) } } extension AccessibilityMarker { enum AccessibilityMarkerType: String, CaseIterable { case button = "Button" case image = "Image" case heading = "Heading" } var type: (type: AccessibilityMarkerType, content: String)? { let string = description guard string.hasSuffix("."), string.count > 1 else { return nil } for type in AccessibilityMarkerType.allCases { if string.hasSuffix(". \(type.rawValue).") { let content = String(string.dropLast(3 + type.rawValue.count)) return (type, content) } } return nil } } #endif
yonaskolb/SwiftComponent
16
Where architecture meets tooling
Swift
yonaskolb
Yonas Kolb
Sources/SwiftPreview/Accessibility/AccessibilityMarkdown.swift
Swift
#if os(iOS) import Foundation import SwiftUI import UIKit import AccessibilitySnapshotCore import RegexBuilder extension AccessibilityHierarchy { public func markdown() -> String { self.filter { !$0.description.trimmingCharacters(in: .whitespaces).isEmpty } .enumerated() .map { $1.markdown(index: $0) } .joined(separator: "\n\n") } } extension AccessibilityMarker { func markdown(index: Int) -> String { var hint = self.hint var action: String? if #available(iOS 16.0, *), let existingHint = hint { let regex = #/action: (.*)/# if let match = existingHint.firstMatch(of: regex) { let actionString = match.output.1 action = String(actionString) hint = existingHint.replacing(regex, with: "") } } var string = "" if let type { switch type.type { case .image: string += "🖼️ " + type.content case .button: string += "[\(type.content)](\(action ?? ""))" case .heading: string += "#### \(type.content)" } } else { string += description } if let hint, !hint.isEmpty { string += " (\(hint))" } if !customActions.isEmpty { string += "\n\(customActions.map { " - [\($0)]()" }.joined(separator: "\n"))" } return string } } struct A11yMarkdown_Previews: PreviewProvider { static var previews: some View { ScrollView { Text(AccessibilityExampleView().accessibilityHierarchy().markdown()) .padding() } } } #endif
yonaskolb/SwiftComponent
16
Where architecture meets tooling
Swift
yonaskolb
Yonas Kolb
Sources/SwiftPreview/Accessibility/AccessibillityView.swift
Swift
#if os(iOS) import Foundation import SwiftUI import AccessibilitySnapshotCore import UIKit extension View { public func accessibilityPreview() -> some View { let hierarchy = self.accessibilityHierarchy() return AccessibilityHierarchyView(hierarchy: hierarchy) } } struct AccessibilityHierarchyView: View { let hierarchy: AccessibilityHierarchy var body: some View { if hierarchy.isEmpty { Text("Accessibility hierarchy not found") } else { ScrollView { LazyVStack(alignment: .leading, spacing: 12) { ForEach(Array(hierarchy.enumerated()), id: \.offset) { index, marker in HStack { markerView(marker) Spacer() } } } .padding() } .frame(maxWidth: .infinity) } } @ViewBuilder func markerView(_ marker: AccessibilityMarker) -> some View { if let type = marker.type { switch type.type { case .button: Button(action: {}) { Text(type.content) .bold() .frame(maxWidth: .infinity) } .buttonStyle(.bordered) case .heading: Text(type.content) .bold() .font(.title2) .padding(.bottom, 8) case .image: HStack { Image(systemName: "photo") Text(type.content) } } } else { Text(marker.description) } } } struct AccessibilityExampleView: View { var body: some View { NavigationView { VStack { Text("My Title") .font(.title) .accessibilityAddTraits(.isHeader) .accessibilityHeading(.h2) Text("Hello, world!") Toggle("Toggle", isOn: .constant(true)) Image(systemName: "person") Picker("Option", selection: .constant(true)) { Text("On").tag(true) Text("Off").tag(false) } .pickerStyle(.segmented) Text("Some really long text. Some really long text. Some really long text. Some really long text. Some really long text. ") Button("Login", action: {}) } .navigationTitle(Text("Nav title")) .toolbar { ToolbarItem(placement: .navigationBarTrailing) { Text("Close") Image(systemName: "plus") } } } } } struct A11yPreviewProvider_Previews: PreviewProvider { static var previews: some View { AccessibilityExampleView().accessibilityPreview() } } #endif
yonaskolb/SwiftComponent
16
Where architecture meets tooling
Swift
yonaskolb
Yonas Kolb
Sources/SwiftPreview/Device.swift
Swift
import Foundation import SwiftUI public struct Device: Equatable { public var name: String public var type: DeviceType public var width: Double public var height: Double var iconType: Icon { switch (homeIndicator, type) { case (true, .iPad): return .iPad case (false, .iPad): return .iPadHome case (true, .iPhone): return .iPhone case (false, .iPhone): return .iPhoneHome case (_, .custom): return .custom } } //TODO: edit these for different devices var bezelWidth: Double = 14 var topSafeAreaHeight: Double = 47 var bottomSafeAreaHeight: Double = 34 var homeIndicator: Bool var notch: Bool var statusBar: Bool = true public var frameSize: CGSize { CGSize(width: width + bezelWidth*2, height: height + bezelWidth*2) } public static let smallPhone = Device(name: "small", type: .custom, width: 320, height: 600, homeIndicator: false, notch: false, statusBar: false) public static let mediumPhone = Device(name: "medium", type: .custom, width: 375, height: 812, homeIndicator: false, notch: false, statusBar: false) public static let largePhone = Device(name: "large", type: .custom, width: 430, height: 932, homeIndicator: false, notch: false, statusBar: false) public static let phone = Device(name: "phone", type: .custom, width: 375, height: 812, homeIndicator: false, notch: false, statusBar: false) public static let iPhoneSE = Device.iPhone(name: "iPhone SE", width: 320, height: 568, homeIndicator: false, notch: false) public static let iPhone13Mini = Device.iPhone(name: "iPhone 13 Mini", width: 375, height: 812) public static let iPhone14 = Device.iPhone(name: "iPhone 14", width: 390, height: 844) public static let iPhone14Plus = Device.iPhone(name: "iPhone 14 Plus", width: 428, height: 926) public static let iPhone14Pro = Device.iPhone(name: "iPhone 14 Pro", width: 393, height: 852) public static let iPhone14ProMax = Device.iPhone(name: "iPhone 14 Pro Max", width: 430, height: 932) public static let iPadAir = Device.iPad(name: "iPad Air", width: 820, height: 1180) public static let iPadMini = Device.iPad(name: "iPad Mini", width: 744, height: 1133) public static let iPad = Device.iPad(name: "iPad", width: 810, height: 1080) public static let iPadPro12 = Device.iPad(name: "iPad Pro 12.9\"", width: 1024, height: 1366) public static let iPadPro11 = Device.iPad(name: "iPad Pro 11\"", width: 834, height: 1194) public static func iPhone(name: String, width: Double, height: Double, homeIndicator: Bool = true, notch: Bool = true) -> Device { Device(name: name, type: .iPhone, width: width, height: height, homeIndicator: homeIndicator, notch: notch) } public static func iPad(name: String, width: Double, height: Double, homeIndicator: Bool = true) -> Device { Device(name: name, type: .iPad, width: width, height: height, bottomSafeAreaHeight: homeIndicator ? 34 : 0, homeIndicator: homeIndicator, notch: false) } public static let iPhones: [Device] = [ iPhoneSE, iPhone13Mini, iPhone14, iPhone14Plus, iPhone14Pro, iPhone14ProMax, ] public static let iPads: [Device] = [ iPadMini, iPadAir, iPad, iPadPro11, iPadPro12, ] public static let all: [Device] = iPhones + iPads public enum DeviceType: String { case iPhone = "iPhone" case iPad = "iPad" case custom = "Custom" } enum Icon: String { case iPhone = "iphone" case iPhoneHome = "iphone.homebutton" case iPad = "ipad" case iPadHome = "ipad.homebutton" case custom = "rectangle.dashed" } public var icon: Image { Image(systemName: iconType.rawValue) } } extension PreviewDevice { public static var iPad: PreviewDevice { PreviewDevice(rawValue: "iPad Pro 11-inch (M4)") } }
yonaskolb/SwiftComponent
16
Where architecture meets tooling
Swift
yonaskolb
Yonas Kolb
Sources/SwiftPreview/DeviceView.swift
Swift
import Foundation import SwiftUI extension View { public func embedIn(device: Device) -> some View { self.modifier(DeviceWrapper(device: device)) } } struct DeviceWrapper: ViewModifier { var device: Device var frameColor = Color(white: 0.05) var borderColor = Color(white: 0.15) var notchHeight: CGFloat = 34 var notchTopRadius: CGFloat = 8 /* NavigationView resets any safe area insets. This means any content that is within a NavigationView won't be inset correctly. A workaround is to push content in but that breaks content content that ignores the safe area like a fullbleed background. */ var insetUsingSafeArea = false var deviceShape: RoundedRectangle { RoundedRectangle(cornerRadius: 40, style: .continuous) } func body(content: Content) -> some View { VStack(spacing: 0) { if device.statusBar, !insetUsingSafeArea { topBar .frame(height: device.topSafeAreaHeight) } content .frame(maxWidth: .infinity, maxHeight: .infinity) if !insetUsingSafeArea { Group { if device.homeIndicator { homeIndicator } } .frame(height: device.bottomSafeAreaHeight, alignment: .bottom) } } .safeAreaInset(edge: .top, spacing: 0) { if device.statusBar, insetUsingSafeArea { topBar .frame(height: device.topSafeAreaHeight) } } .safeAreaInset(edge: .bottom, spacing: 0) { if insetUsingSafeArea { Group { if device.homeIndicator { homeIndicator } } .frame(height: device.bottomSafeAreaHeight, alignment: .bottom) } } .frame(width: device.width, height: device.height) .background(.background) .overlay { deviceShape .inset(by: -device.bezelWidth/2) .stroke(frameColor, lineWidth: device.bezelWidth) deviceShape .inset(by: -device.bezelWidth) .stroke(borderColor, lineWidth: 2) } .clipShape(deviceShape.inset(by: -device.bezelWidth)) .padding(device.bezelWidth) } var topBar: some View { HStack { TimelineView(.periodic(from: .now, by: 1)) { context in // Text(context.date, format: Date.FormatStyle(date: .none, time: .shortened)) Text("9:41 AM") .fontWeight(.medium) .padding(.leading, 24) .frame(maxWidth: .infinity, alignment: .leading) } if device.notch { notch .frame(maxHeight: .infinity, alignment: .top) } HStack { Image(systemName: "wifi") Image(systemName: "battery.100") } .padding(.trailing, 24) .frame(maxWidth: .infinity, alignment: .trailing) } } var notch: some View { let topCorner = CornerShape(cornerRadius: notchTopRadius) .fill(frameColor, style: .init(eoFill: true)) .frame(width: notchTopRadius*2, height: notchTopRadius*2) .frame(width: notchTopRadius, height: notchTopRadius, alignment: .topTrailing) .clipped() return HStack(alignment: .top, spacing: 0) { topCorner RoundedRectangle(cornerRadius: 20, style: .continuous) .fill(frameColor) .frame(height: notchHeight*2) .frame(width: 162, height: notchHeight, alignment: .bottom) topCorner .scaleEffect(x: -1) } } var homeIndicator: some View { Capsule(style: .continuous) .frame(width: 160, height: 5) .frame(height: 13, alignment: .top) } } struct CornerShape: Shape { var cornerRadius: CGFloat func path(in rect: CGRect) -> Path { Path { p in p.addRoundedRect(in: rect, cornerSize: .init(width: cornerRadius, height: cornerRadius), style: .continuous) p.addRect(rect) } } } struct Device_Previews: PreviewProvider { static var previews: some View { Group { NavigationView { ZStack { Color.blue VStack { Spacer() Text("iPhone") Spacer() Text("Bottom") .padding(.bottom, 8) } } .navigationTitle(Text("Title")) #if os(iOS) .navigationBarTitleDisplayMode(.inline) .toolbar { ToolbarItem(placement: .navigationBarTrailing) { Image(systemName: "plus") } } #endif } .embedIn(device: .iPhone14Pro) ZStack { Color.gray Text("iPad") } .embedIn(device: .iPadPro12) ZStack { Color.gray Text("iPad") } .embedIn(device: .phone) } #if os(iOS) .navigationViewStyle(.stack) #endif .previewLayout(.sizeThatFits) .previewDevice(.iPad) } }
yonaskolb/SwiftComponent
16
Where architecture meets tooling
Swift
yonaskolb
Yonas Kolb
Sources/SwiftPreview/Rendering.swift
Swift
#if os(iOS) import SwiftUI import UIKit extension View { public func renderView<T>(in frame: CGRect = UIScreen.main.bounds, render: (UIView) -> T) -> T { let viewController = UIHostingController(rootView: self) var value: T? UIWindow.prepare(viewController: viewController, frame: frame) { value = render(viewController.view) } return value! } } extension UIWindow { static func prepare(viewController: UIViewController, frame: CGRect, render: () -> Void) { let window = UIWindow(frame: frame) UIView.setAnimationsEnabled(false) // use a root view controller so that navigation bar items are shown let rootViewController = UIViewController() rootViewController.view.backgroundColor = .clear rootViewController.view.frame = frame rootViewController.preferredContentSize = frame.size viewController.view.frame = frame rootViewController.view.addSubview(viewController.view) rootViewController.addChild(viewController) viewController.didMove(toParent: rootViewController) window.rootViewController = rootViewController window.makeKeyAndVisible() rootViewController.beginAppearanceTransition(true, animated: false) rootViewController.endAppearanceTransition() rootViewController.view.setNeedsLayout() rootViewController.view.layoutIfNeeded() viewController.view.setNeedsLayout() viewController.view.layoutIfNeeded() // view is ready render() // cleanup window.resignKey() window.rootViewController = nil UIView.setAnimationsEnabled(true) } } #endif
yonaskolb/SwiftComponent
16
Where architecture meets tooling
Swift
yonaskolb
Yonas Kolb
Sources/SwiftPreview/ScalingView.swift
Swift
import Foundation import SwiftUI public enum Scaling: String { case exact case fit } public struct ScalingView<Content: View>: View { let size: CGSize let scaling: Scaling var content: Content public init(size: CGSize, scaling: Scaling = .fit, @ViewBuilder content: () -> Content) { self.size = size self.scaling = scaling self.content = content() } func scale(frame: CGSize) -> CGFloat { min(frame.height / size.height, frame.width / size.width) } public var body: some View { switch scaling { case .exact: ScrollView { content .padding() .frame(maxWidth: .infinity) } case .fit: GeometryReader { proxy in content .scaleEffect(scale(frame: proxy.size)) .frame(width: proxy.size.width, height: proxy.size.height) } .padding() } } }
yonaskolb/SwiftComponent
16
Where architecture meets tooling
Swift
yonaskolb
Yonas Kolb
Tests/SwiftComponentMacroTests/ModelMacroTests.swift
Swift
#if canImport(SwiftComponentMacros) import MacroTesting import Foundation import XCTest import SwiftComponentMacros final class ModelMacroTests: XCTestCase { override func invokeTest() { withMacroTesting(isRecording: false, macros: [ComponentModelMacro.self]) { super.invokeTest() } } func testEmpyModel() { assertMacro { """ @ComponentModel struct Model { } """ } expansion: { """ struct Model { public let _$context: Context public let _$connections: Connections = Self.Connections() public init(context: Context) { self._$context = context } } extension Model: ComponentModel { } """ } } func testDestination() { assertMacro { """ @ComponentModel struct Model { enum Destination { case item(ItemModel.State) } } """ } expansion: { """ struct Model { @ObservableState @CasePathable enum Destination { case item(ItemModel.State) } public let _$context: Context public let _$connections: Connections = Self.Connections() public init(context: Context) { self._$context = context } } extension Model: ComponentModel { } """ } } func testMainActor() { assertMacro { """ @ComponentModel struct Model { let child = Connection<ExampleChildModel>(output: .input(Input.child)) var getter: String { dependencies.something } @MainActor func customFunction() { } func customFunction() { } } """ } expansion: { """ struct Model { @MainActor let child = Connection<ExampleChildModel>(output: .input(Input.child)) @MainActor var getter: String { dependencies.something } @MainActor func customFunction() { } @MainActor func customFunction() { } public let _$context: Context public let _$connections: Connections = Self.Connections() public init(context: Context) { self._$context = context } } extension Model: ComponentModel { } """ } } func testAddObservableState() { assertMacro { """ @ComponentModel struct Model { struct State { } } """ } expansion: { """ struct Model { @ObservableState struct State { } public let _$context: Context public let _$connections: Connections = Self.Connections() public init(context: Context) { self._$context = context } } extension Model: ComponentModel { } """ } } func testKeepObservableState() { assertMacro { """ @ComponentModel struct Model { @ObservableState struct State { } } """ } expansion: { """ struct Model { @ObservableState struct State { } public let _$context: Context public let _$connections: Connections = Self.Connections() public init(context: Context) { self._$context = context } } extension Model: ComponentModel { } """ } } func testKeepExternalObservableState() { assertMacro { """ @ComponentModel struct Model { typealias State = OtherState } """ } expansion: { """ struct Model { typealias State = OtherState public let _$context: Context public let _$connections: Connections = Self.Connections() public init(context: Context) { self._$context = context } } extension Model: ComponentModel { } """ } } } #endif
yonaskolb/SwiftComponent
16
Where architecture meets tooling
Swift
yonaskolb
Yonas Kolb
Tests/SwiftComponentMacroTests/ObservableStateMacroTests.swift
Swift
#if canImport(SwiftComponentMacros) import MacroTesting import Foundation import XCTest import SwiftComponentMacros final class ObservableStateMacroTests: XCTestCase { override func invokeTest() { withMacroTesting(isRecording: false, macros: [ObservableStateMacro.self]) { super.invokeTest() } } func testEmpty() { assertMacro { """ @ObservableState struct State { } """ } expansion: { """ struct State { @ObservationStateIgnored var _$observationRegistrar = SwiftComponent.ObservationStateRegistrar() public var _$id: SwiftComponent.ObservableStateID { _$observationRegistrar.id } public mutating func _$willModify() { _$observationRegistrar._$willModify() } } """ } } func testProperties() { assertMacro { """ @ObservableState struct State { var property: String var property2: Int } """ } expansion: { """ struct State { @ObservationStateTracked var property: String @ObservationStateTracked var property2: Int @ObservationStateIgnored var _$observationRegistrar = SwiftComponent.ObservationStateRegistrar() public var _$id: SwiftComponent.ObservableStateID { _$observationRegistrar.id } public mutating func _$willModify() { _$observationRegistrar._$willModify() } } """ } } func testIgnorePropertyWrapper() { assertMacro { """ @ObservableState struct State { @Resource var property: String } """ } expansion: { """ struct State { @Resource @ObservationStateIgnored var property: String @ObservationStateIgnored var _$observationRegistrar = SwiftComponent.ObservationStateRegistrar() public var _$id: SwiftComponent.ObservableStateID { _$observationRegistrar.id } public mutating func _$willModify() { _$observationRegistrar._$willModify() } } """ } } } #endif
yonaskolb/SwiftComponent
16
Where architecture meets tooling
Swift
yonaskolb
Yonas Kolb
Tests/SwiftComponentMacroTests/ResourceMacroTests.swift
Swift
#if canImport(SwiftComponentMacros) import MacroTesting import Foundation import XCTest import SwiftComponentMacros final class ResourceMacroTests: XCTestCase { override func invokeTest() { withMacroTesting(isRecording: false, macros: [ResourceMacro.self]) { super.invokeTest() } } func testResource() { assertMacro { """ struct State { @Resource var item: Item? @Resource var item2: Item? } """ } expansion: { #""" struct State { var item: Item? { @storageRestrictions(initializes: _item) init(initialValue) { _item = ResourceState(wrappedValue: initialValue) } get { _$observationRegistrar.access(self, keyPath: \.item) return _item.wrappedValue } set { _$observationRegistrar.mutate(self, keyPath: \.item, &_item.wrappedValue, newValue, _$isIdentityEqual) } } var $item: SwiftComponent.ResourceState<Item> { get { _$observationRegistrar.access(self, keyPath: \.item) return _item.projectedValue } set { _$observationRegistrar.mutate(self, keyPath: \.item, &_item.projectedValue, newValue, _$isIdentityEqual) } } @ObservationStateIgnored private var _item = SwiftComponent.ResourceState<Item>(wrappedValue: nil) var item2: Item? { @storageRestrictions(initializes: _item2) init(initialValue) { _item2 = ResourceState(wrappedValue: initialValue) } get { _$observationRegistrar.access(self, keyPath: \.item2) return _item2.wrappedValue } set { _$observationRegistrar.mutate(self, keyPath: \.item2, &_item2.wrappedValue, newValue, _$isIdentityEqual) } } var $item2: SwiftComponent.ResourceState<Item> { get { _$observationRegistrar.access(self, keyPath: \.item2) return _item2.projectedValue } set { _$observationRegistrar.mutate(self, keyPath: \.item2, &_item2.projectedValue, newValue, _$isIdentityEqual) } } @ObservationStateIgnored private var _item2 = SwiftComponent.ResourceState<Item>(wrappedValue: nil) } """# } } } #endif
yonaskolb/SwiftComponent
16
Where architecture meets tooling
Swift
yonaskolb
Yonas Kolb
Tests/SwiftComponentTests/ComponentDescriptionTests.swift
Swift
import Foundation import XCTest import InlineSnapshotTesting @testable import SwiftComponent @available(iOS 16, macOS 13, tvOS 16, watchOS 9, *) final class ComponentDescriptionTests: XCTestCase { func testDescriptionParsing() throws { let description = try ComponentDescription(type: ExampleComponent.self) assertInlineSnapshot(of: description, as: .json) { """ { "component" : { "name" : "ExampleComponent", "states" : [ ], "tests" : [ "Set date", "Fill out", "Open child" ] }, "model" : { "action" : { "enumType" : { "_0" : [ { "name" : "tap", "payloads" : [ "Int" ] }, { "name" : "open", "payloads" : [ ] } ] } }, "connections" : { "structType" : { "_0" : [ { "name" : "child", "type" : "ExampleChildModel" }, { "name" : "connectedChild", "type" : "ExampleChildModel" }, { "name" : "presentedChild", "type" : "ExampleChildModel" }, { "name" : "caseChild", "type" : "ExampleChildModel" } ] } }, "input" : { "enumType" : { "_0" : [ { "name" : "child", "payloads" : [ "Output" ] } ] } }, "name" : "ExampleModel", "output" : { "enumType" : { "_0" : [ { "name" : "finished", "payloads" : [ ] }, { "name" : "unhandled", "payloads" : [ ] } ] } }, "route" : { "enumType" : { "_0" : [ ] } }, "state" : { "structType" : { "_0" : [ { "name" : "name", "type" : "String" }, { "name" : "loading", "type" : "Bool" }, { "name" : "date", "type" : "Date" }, { "name" : "presentedChild", "type" : "State?" }, { "name" : "child", "type" : "State" }, { "name" : "destination", "type" : "Destination?" }, { "name" : "resource", "type" : "ResourceState<String>" } ] } } } } """ } } }
yonaskolb/SwiftComponent
16
Where architecture meets tooling
Swift
yonaskolb
Yonas Kolb
Tests/SwiftComponentTests/ConnectionTests.swift
Swift
import Foundation import XCTest @testable import SwiftComponent @available(iOS 16, macOS 13, tvOS 16, watchOS 9, *) final class ConnectionTests: XCTestCase { @MainActor func testInlineOutput() async { let parent = ViewModel<TestModel>(state: .init()) let child = parent.connectedModel(\.child, state: .init(), id: "constant") await child.sendAsync(.sendOutput) XCTAssertEqual(parent.state.value, "handled") } @MainActor func testConnectedOutput() async { let parent = ViewModel<TestModel>(state: .init()) let child = parent.connectedModel(\.childConnected) await child.sendAsync(.sendOutput) XCTAssertEqual(parent.state.value, "handled") } @MainActor func testDependencies() async { let parent = ViewModel<TestModel>(state: .init()) let child = parent.connectedModel(\.childConnected) await child.sendAsync(.useDependency) XCTAssertEqual(child.state.number, 2) } @MainActor func testConnectedCaching() async { let parent = ViewModel<TestModel>(state: .init()) let child1 = parent.connectedModel(\.childConnected) let child2 = parent.connectedModel(\.childConnected) XCTAssertEqual(child1.id, child2.id) } @MainActor func testStateCaching() async { let parent = ViewModel<TestModel>(state: .init()) let child1 = parent.connectedModel(\.child, state: .init(), id: "1") let child2 = parent.connectedModel(\.child, state: .init(), id: "1") let child3 = parent.connectedModel(\.child, state: .init(), id: "2") XCTAssertEqual(child1.id, child2.id) XCTAssertNotEqual(child2.id, child3.id) } @MainActor func testInputOutput() async { let parent = ViewModel<TestModel>(state: .init()) let child = parent.connectedModel(\.childToInput) await child.sendAsync(.sendOutput) XCTAssertEqual(parent.state.value, "handled") } @MainActor func testActionHandler() async { let parent = ViewModel<TestModel>(state: .init()) let child = parent.connectedModel(\.childAction) await child.sendAsync(.sendOutput) // TODO: fix try? await Task.sleep(for: .seconds(0.1)) // sending action evnent happens via combine publisher right now so incurs a thread hop XCTAssertEqual(parent.state.value, "action handled") } @MainActor func testStateBinding() async { let parent = ViewModel<TestModel>(state: .init()) let child = parent.connectedModel(\.childConnected) await child.sendAsync(.mutateState) XCTAssertEqual(child.state.value, "mutated") XCTAssertEqual(parent.state.child.value, "mutated") } @MainActor func testChildAction() async { let parent = ViewModel<TestModel>(state: .init()) let child = parent.connectedModel(\.childConnected) await parent.sendAsync(.actionToChild) XCTAssertEqual(child.state.value, "from parent") XCTAssertEqual(parent.state.child.value, "from parent") } @MainActor func testPresentedChildAction() async { let parent = ViewModel<TestModel>(state: .init()) parent.state.optionalChild = .init() let child = parent.presentedModel(\.childPresented) await parent.sendAsync(.actionToOptionalChild) XCTAssertEqual(child.wrappedValue?.state.value, "from parent") XCTAssertEqual(parent.state.optionalChild?.value, "from parent") } @MainActor func testParentModelAccess() async { let parent = ViewModel<TestModel>(state: .init()) let child = parent.connections.childConnected await child.sendAsync(.actionToParent) XCTAssertEqual(parent.state.value, "from child") } @MainActor func testChildModelAccess() async { let parent = ViewModel<TestModel>(state: .init()) let child1 = parent.connections.childConnected parent.state.optionalChild = .init() let child2 = parent.presentations.childPresented await parent.sendAsync(.actionToChildren) XCTAssertEqual(child1.state.value, "from parent") XCTAssertEqual(child2.wrappedValue?.state.value, "from parent") } @MainActor func testSiblingModelAccess() async { let parent = ViewModel<TestModel>(state: .init()) let child1 = parent.connections.childConnected parent.state.optionalChild = .init() let child2 = parent.presentations.childPresented await child2.wrappedValue?.sendAsync(.actionToSibling) XCTAssertEqual(child1.state.value, "from sibling") } @ComponentModel fileprivate struct TestModel { struct Connections { let child = Connection<TestModelChild> { $0.model.state.value = "handled" } let childConnected = Connection<TestModelChild> { $0.model.state.value = "handled" } .dependency(\.number, value: 2) .connect(state: \.child) let childPresented = Connection<TestModelChild> { $0.model.state.value = "handled" } .connect(state: \.optionalChild) let childToInput = Connection<TestModelChild>(output: .input(Input.child)).connect(state: \.child) let childAction = Connection<TestModelChild>(output: .ignore) .onAction { $0.model.state.value = "action handled" } .connect(state: \.child) } struct State { var value = "" var optionalChild: TestModelChild.State? var child: TestModelChild.State = .init() } enum Action { case actionToChild case actionToOptionalChild case actionToChildren } enum Input { case child(TestModelChild.Output) } func handle(action: Action) async { switch action { case .actionToChild: await self.connection(\.childConnected) { model in await model.handle(action: .fromParent) } case .actionToOptionalChild: await self.connection(\.child, state: \.optionalChild) { model in await model.handle(action: .fromParent) } case .actionToChildren: await childModel(TestModelChild.self) { $0.state.value = "from parent" } } } func handle(input: Input) async { switch input { case .child(.done): state.value = "handled" } } } @ComponentModel fileprivate struct TestModelChild { struct State { var value: String = "" var number = 0 } enum Action { case sendOutput case mutateState case fromParent case useDependency case actionToParent case actionToSibling } enum Output { case done } func handle(action: Action) async { switch action { case .sendOutput: await outputAsync(.done) case .mutateState: state.value = "mutated" case .fromParent: state.value = "from parent" case .useDependency: state.number = dependencies.number() case .actionToParent: await parentModel(TestModel.self) { $0.state.value = "from child" } case .actionToSibling: await otherModel(TestModelChild.self) { $0.state.value = "from sibling" } } } } }
yonaskolb/SwiftComponent
16
Where architecture meets tooling
Swift
yonaskolb
Yonas Kolb
Tests/SwiftComponentTests/KeyPathTests.swift
Swift
import Foundation import XCTest @testable import SwiftComponent class KeyPathTests: XCTestCase { func testPropertyName() { XCTAssertEqual((\Item.string as KeyPath).propertyName, "string") XCTAssertEqual((\Item.stringOptional as KeyPath).propertyName, "stringOptional") XCTAssertEqual((\Item.stringGetter as KeyPath).propertyName, "stringGetter") XCTAssertEqual((\Item.array[0].string as KeyPath).propertyName, "array.string") XCTAssertEqual((\Item.arrayGetter[0].string as KeyPath).propertyName, "arrayGetter.string") XCTAssertEqual((\Item.child.string as KeyPath).propertyName, "child.string") XCTAssertEqual((\Item.child.array[1].string as KeyPath).propertyName, "child.array.string") XCTAssertEqual((\Item.childOptional?.string as KeyPath).propertyName, "childOptional?.string") XCTAssertEqual((\Item.childGetter.string as KeyPath).propertyName, "childGetter.string") } struct Item { var string: String var stringOptional: String? var stringGetter: String { string } var array: [Child] var arrayGetter: [Child] { array } var child: Child var childOptional: Child? var childGetter: Child { child } } struct Child { var string: String var array: [Child] } }
yonaskolb/SwiftComponent
16
Where architecture meets tooling
Swift
yonaskolb
Yonas Kolb
Tests/SwiftComponentTests/MemoryTests.swift
Swift
import Foundation import XCTest @testable import SwiftComponent @available(iOS 16, macOS 13, tvOS 16, watchOS 9, *) final class MemoryTests: XCTestCase { @MainActor func testMemoryLeak() async { let viewModel = ViewModel<TestModel>(state: .init(child: .init(count: 2))) .dependency(\.continuousClock, ImmediateClock()) await viewModel.appearAsync(first: true) await viewModel.sendAsync(.start) viewModel.disappear() viewModel.appear(first: true) viewModel.send(.start) viewModel.binding(\.count).wrappedValue = 2 _ = viewModel.count let child = viewModel.connectedModel(\.child) await child.appearAsync(first: true) await child.sendAsync(.start) child.send(.start) child.binding(\.count).wrappedValue = 3 _ = child.count let childStateIDAndInput = viewModel.connectedModel(\.childInput, state: .init(), id: "constant") await childStateIDAndInput.disappearAsync() await child.disappearAsync() await viewModel.disappearAsync() try? await Task.sleep(for: .seconds(0.2)) checkForMemoryLeak(viewModel) checkForMemoryLeak(viewModel.store) checkForMemoryLeak(viewModel.store.graph) checkForMemoryLeak(child) checkForMemoryLeak(child.store) checkForMemoryLeak(child.store.graph) checkForMemoryLeak(childStateIDAndInput) checkForMemoryLeak(childStateIDAndInput.store) checkForMemoryLeak(childStateIDAndInput.store.graph) } @ComponentModel fileprivate struct TestModel { struct Connections { let child = Connection<TestModelChild> { $0.model.state.count = 3 }.connect(state: \.child) let childInput = Connection<TestModelChild>(output: .input(Input.child)) } struct State { var count = 0 var optionalChild: TestModelChild.State? var child: TestModelChild.State } enum Action { case start } enum Input { case child(TestModelChild.Output) } func appear() async { await self.task("task") { state.count = 2 } addTask("long running task") { func makeStream() -> AsyncStream<Int> { let stream = AsyncStream.makeStream(of: Int.self) stream.continuation.yield(1) return stream.stream } for await value in makeStream() { } } } func disappear() async { cancelTask("long running task") await self.task("task") { state.count = 0 } } func handle(action: Action) async { switch action { case .start: try? await dependencies.continuousClock.sleep(for: .seconds(0.1)) state.count = 1 await self.task("task") { state.count = 2 } } } func handle(input: Input) async { switch input { case .child(.done): break } } } @ComponentModel fileprivate struct TestModelChild { struct State { var count: Int = 2 } enum Action { case start } enum Output { case done } func appear() async { await self.task("task") { state.count = 2 } } func handle(action: Action) async { switch action { case .start: try? await dependencies.continuousClock.sleep(for: .seconds(0.1)) } } } } extension XCTestCase { func checkForMemoryLeak(_ instance: AnyObject, file: StaticString = #filePath, line: UInt = #line) { addTeardownBlock { [weak instance] in if instance != nil { XCTFail("Instance should have been deallocated", file: file, line: line) } } } }
yonaskolb/SwiftComponent
16
Where architecture meets tooling
Swift
yonaskolb
Yonas Kolb
Tests/SwiftComponentTests/NumberDependency.swift
Swift
import Dependencies struct NumberDependency { let value: Int func callAsFunction() -> Int { value } } extension NumberDependency: ExpressibleByIntegerLiteral { init(integerLiteral value: IntegerLiteralType) { self.value = value } } extension NumberDependency: DependencyKey { static var liveValue = NumberDependency(value: 1) static var testValue = NumberDependency(value: 0) } extension DependencyValues { var number: NumberDependency { get { self[NumberDependency.self] } set { self[NumberDependency.self] = newValue } } }
yonaskolb/SwiftComponent
16
Where architecture meets tooling
Swift
yonaskolb
Yonas Kolb
Tests/SwiftComponentTests/ObservabilityTests.swift
Swift
import Foundation import XCTest @testable import SwiftComponent import Perception @available(iOS 16, macOS 13, tvOS 16, watchOS 9, *) @MainActor final class ObservabilityTests: XCTestCase { var viewModel: ViewModel<Model> = .init(state: .init()) override func setUp() { viewModel = .init(state: .init()) } @ComponentModel struct Model { struct State { var value1 = 1 var value2 = 2 var child: ChildModel.State? @Resource var resource: ResourceData? } struct ResourceData { var value1: String var value2: String } enum Action { case updateValue1 case updateValue2 case setChild case updateChild case reset case loadResource } func handle(action: Action) async { switch action { case .updateValue1: state.value1 += 1 case .updateValue2: state.value2 += 1 case .setChild: state.child = .init() case .updateChild: state.child?.value1 += 1 case .reset: mutate(\.self, .init()) case .loadResource: await loadResource(\.$resource) { ResourceData(value1: "constant", value2: UUID().uuidString) } } } } @ComponentModel struct ChildModel { struct State { var value1 = 1 var value2 = 2 } enum Action { case updateValue1 case updateValue2 } func handle(action: Action) async { switch action { case .updateValue1: state.value1 += 1 case .updateValue2: state.value2 += 1 } } } func test_access_update() { expectUpdate { _ = viewModel.value1 } update: { viewModel.send(.updateValue1) } } func test_reset_update() { expectUpdate { _ = viewModel.value1 } update: { viewModel.send(.reset) } expectUpdate { _ = viewModel.value1 } update: { viewModel.send(.updateValue1) } } func test_other_access_no_update() { expectNoUpdate { _ = viewModel.value2 } update: { viewModel.send(.updateValue1) } } func test_no_access_no_update() { expectNoUpdate { } update: { viewModel.send(.updateValue1) } } func test_child_property_access_update() { viewModel = .init(state: .init(child: .init())) expectUpdate { _ = viewModel.child?.value1 } update: { viewModel.send(.updateChild) } } func test_child_access_no_update() { viewModel = .init(state: .init(child: .init())) expectNoUpdate { _ = viewModel.child } update: { viewModel.send(.updateChild) } } func test_child_set_update() { expectUpdate { _ = viewModel.child } update: { viewModel.send(.setChild) } } func test_child_reset_update() { viewModel = .init(state: .init(child: .init())) expectUpdate { _ = viewModel.child } update: { viewModel.send(.setChild) } } func test_resource_value_update() { expectUpdate { _ = viewModel.resource } update: { viewModel.send(.loadResource) } } func test_resource_property_update() { expectUpdate { _ = viewModel.resource?.value1 } update: { viewModel.send(.loadResource) } } func test_resource_wrapper_update() { expectUpdate { _ = viewModel.$resource } update: { viewModel.send(.loadResource) } } func expectUpdate(access: () -> Void, update: () -> Void) { let expectation = self.expectation(description: "expected update") withPerceptionTracking { access() } onChange: { expectation.fulfill() } update() wait(for: [expectation], timeout: 0.1) } func expectNoUpdate(access: () -> Void, update: () -> Void, file: StaticString = #file, line: UInt = #line) { let expectation = self.expectation(description: "expected update") withPerceptionTracking { access() } onChange: { XCTFail("Didn't expect an update", file: file, line: line) } update() Task { // try? await Task.sleep(for: .seconds(0.05)) expectation.fulfill() } wait(for: [expectation], timeout: 0.2) } }
yonaskolb/SwiftComponent
16
Where architecture meets tooling
Swift
yonaskolb
Yonas Kolb
Tests/SwiftComponentTests/TaskCancellationTests.swift
Swift
import XCTest @testable import SwiftComponent @available(iOS 16, macOS 13, tvOS 16, watchOS 9, *) @MainActor final class TaskCancellationTests: XCTestCase { func test_task_cancels_old_task() async throws { let clock = TestClock() let viewModel = ViewModel<TestModel>(state: .init()) .dependency(\.continuousClock, clock) viewModel.send(.start) await clock.advance(by: .seconds(1)) viewModel.send(.stop) XCTAssertEqual(viewModel.count, 0) await clock.advance(by: .seconds(3)) XCTAssertEqual(viewModel.count, 0) } func test_cancel_task_cancels() async throws { let clock = TestClock() let viewModel = ViewModel<TestModel>(state: .init()) .dependency(\.continuousClock, clock) viewModel.send(.start) await clock.advance(by: .seconds(1.5)) XCTAssertEqual(viewModel.count, 0) viewModel.send(.start) await clock.advance(by: .seconds(1.5)) XCTAssertEqual(viewModel.count, 0) viewModel.send(.stop) await clock.advance(by: .seconds(2)) } func test_cancel_task_tracks_cancellation() async throws { let viewModel = ViewModel<TestModel>(state: .init()) .dependency(\.continuousClock, ImmediateClock()) await viewModel.sendAsync(.addLongRunningTask) await viewModel.sendAsync(.start) XCTAssertEqual(viewModel.store.cancelledTasks, []) await viewModel.sendAsync(.stop) await viewModel.sendAsync(.cancelLongRunningTask) XCTAssertEqual(viewModel.store.cancelledTasks, [TestModel.Task.sleep.rawValue, TestModel.Task.longRunningTask.rawValue]) await viewModel.sendAsync(.start) await viewModel.sendAsync(.addLongRunningTask) XCTAssertEqual(viewModel.store.cancelledTasks, []) await viewModel.sendAsync(.cancelLongRunningTask) } func test_cancel_tasks_cancels() async throws { let clock = TestClock() let viewModel = ViewModel<TestModel>(state: .init()) .dependency(\.continuousClock, clock) viewModel.send(.start) await clock.advance(by: .seconds(1)) viewModel.store.cancelTasks() await clock.advance(by: .seconds(3)) XCTAssertEqual(viewModel.count, 0) } func test_disappear_cancels() async throws { let clock = TestClock() let viewModel = ViewModel<TestModel>(state: .init()) .dependency(\.continuousClock, clock) viewModel.appear(first: true) await clock.advance(by: .seconds(1)) XCTAssertEqual(viewModel.count, 0) viewModel.disappear() await clock.advance(by: .seconds(6)) XCTAssertEqual(viewModel.count, 0) } func test_addTask_cancels() async throws { let clock = TestClock() let viewModel = ViewModel<TestModel>(state: .init()) .dependency(\.continuousClock, clock) viewModel.send(.addLongRunningTask) await clock.advance(by: .seconds(1.5)) XCTAssertEqual(viewModel.count, 1) viewModel.send(.cancelLongRunningTask) await clock.advance(by: .seconds(2)) XCTAssertEqual(viewModel.count, 1) await clock.advance(by: .seconds(2)) } @ComponentModel struct TestModel { struct State { var count = 0 } enum Task: String, ModelTask { case sleep case longRunningTask } enum Action { case start case stop case addLongRunningTask case cancelLongRunningTask } func appear() async { do { try await dependencies.continuousClock.sleep(for: .seconds(2)) state.count = 1 await task(.sleep) { do { try await dependencies.continuousClock.sleep(for: .seconds(3)) state.count = 2 } catch {} } } catch { } } func handle(action: Action) async { switch action { case .start: await task(.sleep, cancellable: true) { do { try await dependencies.continuousClock.sleep(for: .seconds(2)) state.count = 1 } catch {} } case .stop: cancelTask(.sleep) case .addLongRunningTask: addTask(.longRunningTask) { func makeStream() -> AsyncStream<Int> { let stream = AsyncStream.makeStream(of: Int.self) stream.continuation.yield(1) return stream.stream } for await value in makeStream() { state.count += value } } case .cancelLongRunningTask: cancelTask(.longRunningTask) } } } }
yonaskolb/SwiftComponent
16
Where architecture meets tooling
Swift
yonaskolb
Yonas Kolb
cmd/main.go
Go
package main import ( "net/http" "github.com/go-chi/chi/v5" chiMiddleware "github.com/go-chi/chi/v5/middleware" httpSwagger "github.com/swaggo/http-swagger" "go.uber.org/zap" "github.com/yorukot/starker/internal/config" "github.com/yorukot/starker/internal/database" "github.com/yorukot/starker/internal/handler" "github.com/yorukot/starker/internal/middleware" "github.com/yorukot/starker/internal/router" "github.com/yorukot/starker/pkg/logger" "github.com/yorukot/starker/pkg/response" _ "github.com/golang-migrate/migrate/v4/database/postgres" _ "github.com/golang-migrate/migrate/v4/source/file" _ "github.com/joho/godotenv/autoload" _ "github.com/yorukot/starker/docs" ) // @title starker Go API Template // @version 1.0 // @description starker Go API Template // @termsOfService http://swagger.io/terms/ // @contact.name API Support // @contact.url http://www.swagger.io/support // @contact.email support@swagger.io // @license.name MIT // @license.url https://opensource.org/licenses/MIT // @host localhost:8000 // @BasePath /api // @schemes http https // Run starts the server func main() { logger.InitLogger() _, err := config.InitConfig() if err != nil { zap.L().Fatal("Error initializing config", zap.Error(err)) return } r := chi.NewRouter() db, err := database.InitDatabase() if err != nil { zap.L().Fatal("Failed to initialize database", zap.Error(err)) } defer db.Close() r.Use(middleware.ZapLoggerMiddleware(zap.L())) r.Use(chiMiddleware.StripSlashes) setupRouter(r, &handler.App{DB: db}) zap.L().Info("Starting server on http://localhost:" + config.Env().Port) zap.L().Info("Environment: " + string(config.Env().AppEnv)) err = http.ListenAndServe(":"+config.Env().Port, r) if err != nil { zap.L().Fatal("Failed to start server", zap.Error(err)) } } // setupRouter sets up the router func setupRouter(r chi.Router, app *handler.App) { r.Route("/api", func(r chi.Router) { router.AuthRouter(r, app) router.NodeRouter(r, app) }) if config.Env().AppEnv == config.AppEnvDev { r.Get("/swagger/*", httpSwagger.WrapHandler) } r.Get("/health", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("OK")) }) // Not found handler r.NotFound(func(w http.ResponseWriter, r *http.Request) { response.RespondWithError(w, http.StatusNotFound, "Not Found", "NOT_FOUND") }) r.MethodNotAllowed(func(w http.ResponseWriter, r *http.Request) { response.RespondWithError(w, http.StatusMethodNotAllowed, "Method Not Allowed", "METHOD_NOT_ALLOWED") }) zap.L().Info("Router setup complete") }
yorukot/Houng
1
Go
yorukot
Yorukot
docs/docs.go
Go
// Package docs Code generated by swaggo/swag. DO NOT EDIT package docs import "github.com/swaggo/swag" const docTemplate = `{ "schemes": {{ marshal .Schemes }}, "swagger": "2.0", "info": { "description": "{{escape .Description}}", "title": "{{.Title}}", "termsOfService": "http://swagger.io/terms/", "contact": { "name": "API Support", "url": "http://www.swagger.io/support", "email": "support@swagger.io" }, "license": { "name": "MIT", "url": "https://opensource.org/licenses/MIT" }, "version": "{{.Version}}" }, "host": "{{.Host}}", "basePath": "{{.BasePath}}", "paths": { "/auth/login": { "post": { "description": "Authenticates a user with email and password, returns a refresh token cookie", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "auth" ], "summary": "User login", "parameters": [ { "description": "Login request", "name": "request", "in": "body", "required": true, "schema": { "$ref": "#/definitions/authsvc.LoginRequest" } } ], "responses": { "200": { "description": "Login successful", "schema": { "type": "string" } }, "400": { "description": "Invalid request body, user not found, or invalid password", "schema": { "$ref": "#/definitions/response.ErrorResponse" } }, "500": { "description": "Internal server error", "schema": { "$ref": "#/definitions/response.ErrorResponse" } } } } }, "/collections": { "get": { "description": "Gets all collections with their hierarchical structure and associated monitors", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "collections" ], "summary": "Get all collections", "responses": { "200": { "description": "List of collections with their children and monitors", "schema": { "type": "array", "items": { "$ref": "#/definitions/collectionsvc.CollectionWithDetails" } } }, "500": { "description": "Internal server error", "schema": { "$ref": "#/definitions/response.ErrorResponse" } } } }, "post": { "description": "Creates a new collection with optional parent collection", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "collections" ], "summary": "Create a new collection", "parameters": [ { "description": "Create collection request", "name": "request", "in": "body", "required": true, "schema": { "$ref": "#/definitions/collectionsvc.CreateCollectionRequest" } } ], "responses": { "201": { "description": "Collection created successfully", "schema": { "$ref": "#/definitions/models.Collection" } }, "400": { "description": "Invalid request body or parent collection not found", "schema": { "$ref": "#/definitions/response.ErrorResponse" } }, "500": { "description": "Internal server error", "schema": { "$ref": "#/definitions/response.ErrorResponse" } } } } }, "/collections/{collectionID}": { "delete": { "description": "Deletes a collection if it has no child collections or monitors", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "collections" ], "summary": "Delete a collection", "parameters": [ { "type": "string", "description": "Collection ID", "name": "collectionID", "in": "path", "required": true } ], "responses": { "200": { "description": "Collection deleted successfully", "schema": { "type": "string" } }, "400": { "description": "Collection not found, has child collections, or has monitors", "schema": { "$ref": "#/definitions/response.ErrorResponse" } }, "500": { "description": "Internal server error", "schema": { "$ref": "#/definitions/response.ErrorResponse" } } } }, "patch": { "description": "Updates an existing collection with new name and/or parent collection", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "collections" ], "summary": "Update a collection", "parameters": [ { "type": "string", "description": "Collection ID", "name": "collectionID", "in": "path", "required": true }, { "description": "Update collection request", "name": "request", "in": "body", "required": true, "schema": { "$ref": "#/definitions/collectionsvc.UpdateCollectionRequest" } } ], "responses": { "200": { "description": "Collection updated successfully", "schema": { "$ref": "#/definitions/models.Collection" } }, "400": { "description": "Invalid request body or collection not found", "schema": { "$ref": "#/definitions/response.ErrorResponse" } }, "500": { "description": "Internal server error", "schema": { "$ref": "#/definitions/response.ErrorResponse" } } } } }, "/monitors/{monitorID}": { "get": { "description": "Retrieves a specific monitor configuration by its ID", "produces": [ "application/json" ], "tags": [ "monitor" ], "summary": "Get a monitor by ID", "parameters": [ { "type": "string", "description": "Monitor ID", "name": "monitorID", "in": "path", "required": true } ], "responses": { "200": { "description": "Monitor retrieved successfully", "schema": { "$ref": "#/definitions/models.Monitor" } }, "400": { "description": "Monitor ID is required", "schema": { "$ref": "#/definitions/response.ErrorResponse" } }, "404": { "description": "Monitor not found", "schema": { "$ref": "#/definitions/response.ErrorResponse" } }, "500": { "description": "Internal server error", "schema": { "$ref": "#/definitions/response.ErrorResponse" } } } }, "put": { "description": "Updates an existing monitor configuration by its ID", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "monitor" ], "summary": "Update an existing monitor", "parameters": [ { "type": "string", "description": "Monitor ID", "name": "monitorID", "in": "path", "required": true }, { "description": "Monitor update request", "name": "request", "in": "body", "required": true, "schema": { "$ref": "#/definitions/monitorsvc.UpdateMonitorRequest" } } ], "responses": { "200": { "description": "Monitor updated successfully", "schema": { "$ref": "#/definitions/models.Monitor" } }, "400": { "description": "Invalid request body or monitor/collection not found", "schema": { "$ref": "#/definitions/response.ErrorResponse" } }, "404": { "description": "Monitor not found", "schema": { "$ref": "#/definitions/response.ErrorResponse" } }, "500": { "description": "Internal server error", "schema": { "$ref": "#/definitions/response.ErrorResponse" } } } } }, "/monitors/{monitorID}/ping": { "post": { "description": "Executes a ping operation for the specified monitor and stores the result", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "monitor" ], "summary": "Execute a ping operation for a monitor", "parameters": [ { "type": "string", "description": "Monitor ID", "name": "monitorID", "in": "path", "required": true }, { "type": "string", "default": "Bearer your-node-token", "description": "Bearer token for node authentication", "name": "Authorization", "in": "header", "required": true }, { "description": "Ping request with timestamp and latency data", "name": "request", "in": "body", "required": true, "schema": { "$ref": "#/definitions/monitorsvc.PingRequest" } } ], "responses": { "200": { "description": "Ping executed successfully", "schema": { "$ref": "#/definitions/models.Ping" } }, "400": { "description": "Invalid request or monitor not found", "schema": { "$ref": "#/definitions/response.ErrorResponse" } }, "401": { "description": "Invalid authentication token", "schema": { "$ref": "#/definitions/response.ErrorResponse" } }, "500": { "description": "Internal server error", "schema": { "$ref": "#/definitions/response.ErrorResponse" } } } } }, "/nodes": { "get": { "description": "Get all nodes", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "nodes" ], "summary": "Get all nodes", "responses": { "200": { "description": "Nodes fetched successfully", "schema": { "type": "array", "items": { "$ref": "#/definitions/models.Node" } } }, "500": { "description": "Internal server error", "schema": { "$ref": "#/definitions/response.ErrorResponse" } } } }, "post": { "description": "Creates a new infrastructure node with IP and optional name", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "nodes" ], "summary": "Create a new node", "parameters": [ { "description": "Node creation request", "name": "request", "in": "body", "required": true, "schema": { "$ref": "#/definitions/nodesvc.CreateNodeRequest" } } ], "responses": { "200": { "description": "Node created successfully", "schema": { "$ref": "#/definitions/models.Node" } }, "400": { "description": "Invalid request body or IP already in use", "schema": { "$ref": "#/definitions/response.ErrorResponse" } }, "500": { "description": "Internal server error", "schema": { "$ref": "#/definitions/response.ErrorResponse" } } } } }, "/nodes/monitors/{nodeID}": { "post": { "description": "Creates a new monitor configuration for the specified node", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "monitor" ], "summary": "Create a new monitor", "parameters": [ { "type": "string", "description": "Node ID", "name": "nodeID", "in": "path", "required": true }, { "description": "Monitor creation request", "name": "request", "in": "body", "required": true, "schema": { "$ref": "#/definitions/monitorsvc.CreateMonitorRequest" } } ], "responses": { "200": { "description": "Monitor created successfully", "schema": { "$ref": "#/definitions/models.Monitor" } }, "400": { "description": "Invalid request body or node not found", "schema": { "$ref": "#/definitions/response.ErrorResponse" } }, "500": { "description": "Internal server error", "schema": { "$ref": "#/definitions/response.ErrorResponse" } } } } }, "/nodes/{nodeID}": { "delete": { "description": "Deletes a node by ID. Node cannot be deleted if it has associated monitors", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "nodes" ], "summary": "Delete a node", "parameters": [ { "type": "string", "description": "Node ID", "name": "nodeID", "in": "path", "required": true } ], "responses": { "200": { "description": "Node deleted successfully", "schema": { "type": "string" } }, "400": { "description": "Invalid node ID or node has associated monitors", "schema": { "$ref": "#/definitions/response.ErrorResponse" } }, "404": { "description": "Node not found", "schema": { "$ref": "#/definitions/response.ErrorResponse" } }, "500": { "description": "Internal server error", "schema": { "$ref": "#/definitions/response.ErrorResponse" } } } }, "patch": { "description": "Updates a node's information (currently only name)", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "nodes" ], "summary": "Update a node", "parameters": [ { "type": "string", "description": "Node ID", "name": "nodeID", "in": "path", "required": true }, { "description": "Node update request", "name": "request", "in": "body", "required": true, "schema": { "$ref": "#/definitions/nodesvc.UpdateNodeRequest" } } ], "responses": { "200": { "description": "Node updated successfully", "schema": { "$ref": "#/definitions/models.Node" } }, "400": { "description": "Invalid request body or node ID", "schema": { "$ref": "#/definitions/response.ErrorResponse" } }, "404": { "description": "Node not found", "schema": { "$ref": "#/definitions/response.ErrorResponse" } }, "500": { "description": "Internal server error", "schema": { "$ref": "#/definitions/response.ErrorResponse" } } } } } }, "definitions": { "authsvc.LoginRequest": { "type": "object", "required": [ "email", "password" ], "properties": { "email": { "type": "string", "maxLength": 255 }, "password": { "type": "string", "maxLength": 255, "minLength": 8 } } }, "collectionsvc.CollectionWithDetails": { "type": "object", "properties": { "children": { "type": "array", "items": { "$ref": "#/definitions/collectionsvc.CollectionWithDetails" } }, "created_at": { "description": "Timestamp when the collection was created", "type": "string", "example": "2023-01-01T12:00:00Z" }, "id": { "description": "Unique identifier for the collection", "type": "string", "example": "01ARZ3NDEKTSV4RRFFQ69G5FAV" }, "monitors": { "type": "array", "items": { "$ref": "#/definitions/models.Monitor" } }, "name": { "description": "Name of the collection", "type": "string", "example": "Production Servers" }, "parent_collection_id": { "description": "Optional parent collection ID for hierarchy", "type": "string", "example": "01ARZ3NDEKTSV4RRFFQ" }, "updated_at": { "description": "Timestamp when the collection was last updated", "type": "string", "example": "2023-01-01T12:00:00Z" } } }, "collectionsvc.CreateCollectionRequest": { "type": "object", "required": [ "name" ], "properties": { "name": { "type": "string", "maxLength": 255 }, "parent_collection_id": { "type": "string" } } }, "collectionsvc.UpdateCollectionRequest": { "type": "object", "properties": { "name": { "type": "string", "maxLength": 255 }, "parent_collection_id": { "type": "string" } } }, "models.Collection": { "type": "object", "properties": { "created_at": { "description": "Timestamp when the collection was created", "type": "string", "example": "2023-01-01T12:00:00Z" }, "id": { "description": "Unique identifier for the collection", "type": "string", "example": "01ARZ3NDEKTSV4RRFFQ69G5FAV" }, "name": { "description": "Name of the collection", "type": "string", "example": "Production Servers" }, "parent_collection_id": { "description": "Optional parent collection ID for hierarchy", "type": "string", "example": "01ARZ3NDEKTSV4RRFFQ" }, "updated_at": { "description": "Timestamp when the collection was last updated", "type": "string", "example": "2023-01-01T12:00:00Z" } } }, "models.Monitor": { "type": "object", "properties": { "collection_id": { "description": "ID of the collection this monitor belongs to", "type": "string", "example": "01ARZ3NDEKTSV4RRFFQ" }, "created_at": { "description": "Timestamp when the monitor was created", "type": "string", "example": "2023-01-01T12:00:00Z" }, "from": { "description": "ID of the node performing the monitoring", "type": "string", "example": "01ARZ3NDEKTSV4RRFFQ69G5FAV" }, "id": { "description": "Unique identifier for the monitor", "type": "string", "example": "01ARZ3NDEKTSV4RRFFQ69G5FAV" }, "name": { "description": "Name of the monitoring configuration", "type": "string", "example": "Web Server Health Check" }, "to_ip": { "description": "Target IP address to monitor", "type": "string", "example": "192.168.1.200" }, "to_name": { "description": "Optional name for the target", "type": "string", "example": "web-server-02" }, "updated_at": { "description": "Timestamp when the monitor was last updated", "type": "string", "example": "2023-01-01T12:00:00Z" } } }, "models.Node": { "type": "object", "properties": { "created_at": { "description": "Timestamp when the node was created", "type": "string", "example": "2023-01-01T12:00:00Z" }, "id": { "description": "Unique identifier for the node", "type": "string", "example": "01ARZ3NDEKTSV4RRFFQ69G5FAV" }, "ip": { "description": "IP address of the node", "type": "string", "example": "192.168.1.100" }, "name": { "description": "Optional name for the node", "type": "string", "example": "web-server-01" }, "token": { "description": "Authentication token for the node", "type": "string", "example": "node_auth_token_123" }, "updated_at": { "description": "Timestamp when the node was last updated", "type": "string", "example": "2023-01-01T12:00:00Z" } } }, "models.Ping": { "type": "object", "properties": { "latency_ms": { "description": "Response time in milliseconds (nullable)", "type": "number", "example": 25.5 }, "node_id": { "description": "ID of the node that performed the ping", "type": "string", "example": "01ARZ3NDEKTSV4RRFFQ69G5FAV" }, "packet_loss": { "description": "Whether the ping resulted in packet loss", "type": "boolean", "example": false }, "ping_id": { "description": "Unique identifier for the ping", "type": "string", "example": "01ARZ3NDEKTSV4RRFFQ69G5FAV" }, "time": { "description": "Timestamp when the ping was performed", "type": "string", "example": "2023-01-01T12:00:00Z" } } }, "monitorsvc.CreateMonitorRequest": { "type": "object", "required": [ "collection_id", "name", "to_ip" ], "properties": { "collection_id": { "type": "string" }, "name": { "type": "string", "maxLength": 255 }, "to_ip": { "type": "string" }, "to_name": { "type": "string", "maxLength": 255 } } }, "monitorsvc.PingRequest": { "type": "object", "required": [ "timestamp" ], "properties": { "latency_ms": { "description": "Ping latency in milliseconds (nil if packet loss)", "type": "number", "minimum": 0 }, "packet_loss": { "description": "Whether packet loss occurred", "type": "boolean" }, "timestamp": { "description": "Unix timestamp when the ping was performed by the node", "type": "integer" } } }, "monitorsvc.UpdateMonitorRequest": { "type": "object", "properties": { "collection_id": { "type": "string" }, "name": { "type": "string", "maxLength": 255 }, "to_ip": { "type": "string" }, "to_name": { "type": "string", "maxLength": 255 } } }, "nodesvc.CreateNodeRequest": { "type": "object", "required": [ "ip" ], "properties": { "ip": { "type": "string" }, "name": { "type": "string", "maxLength": 255 } } }, "nodesvc.UpdateNodeRequest": { "type": "object", "properties": { "name": { "type": "string", "maxLength": 255 } } }, "response.ErrorResponse": { "type": "object", "properties": { "err_code": { "type": "string" }, "message": { "type": "string" } } } } }` // SwaggerInfo holds exported Swagger Info so clients can modify it var SwaggerInfo = &swag.Spec{ Version: "1.0", Host: "localhost:8000", BasePath: "/api", Schemes: []string{"http", "https"}, Title: "starker Go API Template", Description: "starker Go API Template", InfoInstanceName: "swagger", SwaggerTemplate: docTemplate, LeftDelim: "{{", RightDelim: "}}", } func init() { swag.Register(SwaggerInfo.InstanceName(), SwaggerInfo) }
yorukot/Houng
1
Go
yorukot
Yorukot
internal/config/env.go
Go
package config import ( "sync" "github.com/caarlos0/env/v10" "go.uber.org/zap" ) type AppEnv string const ( AppEnvDev AppEnv = "dev" AppEnvProd AppEnv = "prod" ) // EnvConfig holds all environment variables for the application type EnvConfig struct { AdminPassword string `env:"ADMIN_PASSWORD,required"` AdminEmail string `env:"ADMIN_EMAIL,required"` JWTSecretKey string `env:"JWT_SECRET_KEY,required"` DBHost string `env:"DB_HOST,required"` DBPort string `env:"DB_PORT,required"` DBUser string `env:"DB_USER,required"` DBPassword string `env:"DB_PASSWORD,required"` DBName string `env:"DB_NAME,required"` DBSSLMode string `env:"DB_SSL_MODE,required"` AccessTokenExpiresAt int `env:"ACCESS_TOKEN_EXPIRES_AT" envDefault:"604800"` // 7 days Port string `env:"PORT" envDefault:"8080"` Debug bool `env:"DEBUG" envDefault:"false"` AppEnv AppEnv `env:"APP_ENV" envDefault:"prod"` AppName string `env:"APP_NAME" envDefault:"starker"` } var ( appConfig *EnvConfig once sync.Once ) // loadConfig loads and validates all environment variables func loadConfig() (*EnvConfig, error) { cfg := &EnvConfig{} if err := env.Parse(cfg); err != nil { return nil, err } return cfg, nil } // InitConfig initializes the config only once func InitConfig() (*EnvConfig, error) { var err error once.Do(func() { appConfig, err = loadConfig() zap.L().Info("Config loaded") }) return appConfig, err } // Env returns the config. Panics if not initialized. func Env() *EnvConfig { if appConfig == nil { zap.L().Panic("config not initialized — call InitConfig() first") } return appConfig }
yorukot/Houng
1
Go
yorukot
Yorukot
internal/database/postgresql.go
Go
package database import ( "context" "errors" "fmt" "os" "github.com/golang-migrate/migrate/v4" "github.com/jackc/pgx/v5/pgxpool" "go.uber.org/zap" "github.com/yorukot/starker/internal/config" ) // InitDatabase initialize the database connection pool and return the pool and also migrate the database func InitDatabase() (*pgxpool.Pool, error) { ctx := context.Background() pool, err := pgxpool.New(ctx, getDatabaseURL()) if err != nil { return nil, err } if err := pool.Ping(ctx); err != nil { pool.Close() return nil, err } zap.L().Info("Database initialized") Migrator() return pool, nil } // getDatabaseURL return a pgsql connection uri by the environment variables func getDatabaseURL() string { dbHost := config.Env().DBHost dbPort := config.Env().DBPort dbUser := config.Env().DBUser dbPassword := config.Env().DBPassword dbName := config.Env().DBName dbSSLMode := config.Env().DBSSLMode if dbSSLMode == "" { dbSSLMode = "disable" } return fmt.Sprintf( "postgres://%s:%s@%s:%s/%s?sslmode=%s", dbUser, dbPassword, dbHost, dbPort, dbName, dbSSLMode, ) } // Migrator the database func Migrator() { zap.L().Info("Migrating database") wd, _ := os.Getwd() databaseURL := getDatabaseURL() migrationsPath := "file://" + wd + "/migrations" m, err := migrate.New(migrationsPath, databaseURL) if err != nil { zap.L().Fatal("failed to create migrator", zap.Error(err)) } if err := m.Up(); err != nil && !errors.Is(err, migrate.ErrNoChange) { zap.L().Fatal("failed to migrate database", zap.Error(err)) } zap.L().Info("Database migrated") }
yorukot/Houng
1
Go
yorukot
Yorukot
internal/handler/auth/auth.go
Go
// Package auth provides the auth handler. package auth import ( "encoding/json" "net/http" "go.uber.org/zap" "github.com/yorukot/starker/internal/config" "github.com/yorukot/starker/internal/service/authsvc" "github.com/yorukot/starker/pkg/response" ) // +----------------------------------------------+ // | Login | // +----------------------------------------------+ // Login godoc // @Summary User login // @Description Authenticates a user with email and password, returns a refresh token cookie // @Tags auth // @Accept json // @Produce json // @Param request body authsvc.LoginRequest true "Login request" // @Success 200 {object} string "Login successful" // @Failure 400 {object} response.ErrorResponse "Invalid request body, user not found, or invalid password" // @Failure 500 {object} response.ErrorResponse "Internal server error" // @Router /auth/login [post] func (h *AuthHandler) Login(w http.ResponseWriter, r *http.Request) { // Decode the request body var loginRequest authsvc.LoginRequest if err := json.NewDecoder(r.Body).Decode(&loginRequest); err != nil { response.RespondWithError(w, http.StatusBadRequest, "Invalid request body", "INVALID_REQUEST_BODY") return } // Validate the request body if err := authsvc.LoginValidate(loginRequest); err != nil { response.RespondWithError(w, http.StatusBadRequest, "Invalid request body", "INVALID_REQUEST_BODY") return } if loginRequest.Email != config.Env().AdminEmail || loginRequest.Password != config.Env().AdminPassword { response.RespondWithError(w, http.StatusBadRequest, "Invalid credentials", "INVALID_CREDENTIALS") return } // Generate the access token accessToken, err := authsvc.GenerateAccessToken(r.Context(), loginRequest.Email) if err != nil { zap.L().Error("Failed to generate refresh token", zap.Error(err)) response.RespondWithError(w, http.StatusInternalServerError, "Failed to generate access token", "FAILED_TO_GENERATE_ACCESS_TOKEN") return } accessTokenCookie, err := authsvc.GenerateAccessTokenCookie(accessToken) if err != nil { zap.L().Error("Failed to generate access token cookie", zap.Error(err)) response.RespondWithError(w, http.StatusInternalServerError, "Failed to generate access token cookie", "FAILED_TO_GENERATE_ACCESS_TOKEN_COOKIE") return } http.SetCookie(w, &accessTokenCookie) response.RespondWithJSON(w, http.StatusOK, "Login successful", nil) }
yorukot/Houng
1
Go
yorukot
Yorukot
internal/handler/auth/handler.go
Go
package auth import ( "github.com/jackc/pgx/v5/pgxpool" ) // AuthHandler is the handler for the auth routes type AuthHandler struct { DB *pgxpool.Pool }
yorukot/Houng
1
Go
yorukot
Yorukot
internal/handler/collection/create.go
Go
package collection import ( "encoding/json" "net/http" "go.uber.org/zap" "github.com/yorukot/starker/internal/repository" "github.com/yorukot/starker/internal/service/collectionsvc" "github.com/yorukot/starker/pkg/response" ) // +----------------------------------------------+ // | Create Collection | // +----------------------------------------------+ // CreateCollection godoc // @Summary Create a new collection // @Description Creates a new collection with optional parent collection // @Tags collections // @Accept json // @Produce json // @Param request body collectionsvc.CreateCollectionRequest true "Create collection request" // @Success 201 {object} models.Collection "Collection created successfully" // @Failure 400 {object} response.ErrorResponse "Invalid request body or parent collection not found" // @Failure 500 {object} response.ErrorResponse "Internal server error" // @Router /collections [post] func (h *CollectionHandler) CreateCollection(w http.ResponseWriter, r *http.Request) { // Check if the payload is valid var createRequest collectionsvc.CreateCollectionRequest if err := json.NewDecoder(r.Body).Decode(&createRequest); err != nil { response.RespondWithError(w, http.StatusBadRequest, "Invalid request body", "INVALID_REQUEST_BODY") return } // Validate the request body if err := collectionsvc.CreateCollectionValidate(createRequest); err != nil { response.RespondWithError(w, http.StatusBadRequest, "Invalid request body", "INVALID_REQUEST_BODY") return } // Start the transaction tx, err := repository.StartTransaction(h.DB, r.Context()) if err != nil { zap.L().Error("Failed to begin transaction", zap.Error(err)) response.RespondWithError(w, http.StatusInternalServerError, "Failed to begin transaction", "FAILED_TO_BEGIN_TRANSACTION") return } defer repository.DeferRollback(tx, r.Context()) // If the parent is exist check if it is exists if createRequest.ParentCollectionID != nil { parentCollection, err := repository.GetCollectionByID(r.Context(), tx, *createRequest.ParentCollectionID) if err != nil { zap.L().Error("Failed to check parent collection", zap.Error(err)) response.RespondWithError(w, http.StatusInternalServerError, "Failed to check parent collection", "FAILED_TO_CHECK_PARENT_COLLECTION") return } if parentCollection == nil { response.RespondWithError(w, http.StatusBadRequest, "Parent collection not found", "PARENT_COLLECTION_NOT_FOUND") return } } // Create the collection collection := collectionsvc.GenerateCollection(createRequest) if err = repository.CreateCollection(r.Context(), tx, collection); err != nil { zap.L().Error("Failed to create collection", zap.Error(err)) response.RespondWithError(w, http.StatusInternalServerError, "Failed to create collection", "FAILED_TO_CREATE_COLLECTION") return } // Commit the transaction repository.CommitTransaction(tx, r.Context()) // Return the response with the collection response.RespondWithJSON(w, http.StatusCreated, "Collection created successfully", collection) }
yorukot/Houng
1
Go
yorukot
Yorukot
internal/handler/collection/delete.go
Go
package collection import ( "net/http" "github.com/go-chi/chi/v5" "go.uber.org/zap" "github.com/yorukot/starker/internal/repository" "github.com/yorukot/starker/pkg/response" ) // +----------------------------------------------+ // | Delete Collection | // +----------------------------------------------+ // DeleteCollection godoc // @Summary Delete a collection // @Description Deletes a collection if it has no child collections or monitors // @Tags collections // @Accept json // @Produce json // @Param collectionID path string true "Collection ID" // @Success 200 {object} string "Collection deleted successfully" // @Failure 400 {object} response.ErrorResponse "Collection not found, has child collections, or has monitors" // @Failure 500 {object} response.ErrorResponse "Internal server error" // @Router /collections/{collectionID} [delete] func (h *CollectionHandler) DeleteCollection(w http.ResponseWriter, r *http.Request) { // Get the collection ID from the request collectionID := chi.URLParam(r, "collectionID") // Start the transaction tx, err := repository.StartTransaction(h.DB, r.Context()) if err != nil { zap.L().Error("Failed to begin transaction", zap.Error(err)) response.RespondWithError(w, http.StatusInternalServerError, "Failed to begin transaction", "FAILED_TO_BEGIN_TRANSACTION") return } defer repository.DeferRollback(tx, r.Context()) // Get the collection from the database and also check if the collection is exists collection, err := repository.GetCollectionByID(r.Context(), tx, collectionID) if err != nil { zap.L().Error("Failed to get collection by ID", zap.Error(err)) response.RespondWithError(w, http.StatusInternalServerError, "Failed to get collection by ID", "FAILED_TO_GET_COLLECTION_BY_ID") return } if collection == nil { response.RespondWithError(w, http.StatusBadRequest, "Collection not found", "COLLECTION_NOT_FOUND") return } // Check if the collection has any children childCollections, err := repository.GetCollectionsByParentID(r.Context(), tx, collectionID) if err != nil { zap.L().Error("Failed to get child collections", zap.Error(err)) response.RespondWithError(w, http.StatusInternalServerError, "Failed to get child collections", "FAILED_TO_GET_CHILD_COLLECTIONS") return } if len(childCollections) > 0 { response.RespondWithError(w, http.StatusBadRequest, "Cannot delete collection with child collections", "COLLECTION_HAS_CHILDREN") return } // Check if the collection has any monitors monitors, err := repository.GetMonitorsByCollectionID(r.Context(), tx, collectionID) if err != nil { zap.L().Error("Failed to get monitors by collection ID", zap.Error(err)) response.RespondWithError(w, http.StatusInternalServerError, "Failed to get monitors by collection ID", "FAILED_TO_GET_MONITORS_BY_COLLECTION_ID") return } if len(monitors) > 0 { response.RespondWithError(w, http.StatusBadRequest, "Cannot delete collection with monitors", "COLLECTION_HAS_MONITORS") return } // Delete the collection if err = repository.DeleteCollectionByID(r.Context(), tx, collectionID); err != nil { zap.L().Error("Failed to delete collection", zap.Error(err)) response.RespondWithError(w, http.StatusInternalServerError, "Failed to delete collection", "FAILED_TO_DELETE_COLLECTION") return } // Commit the transaction repository.CommitTransaction(tx, r.Context()) // Return the response with the collection response.RespondWithJSON(w, http.StatusOK, "Collection deleted successfully", nil) }
yorukot/Houng
1
Go
yorukot
Yorukot
internal/handler/collection/get.go
Go
package collection import ( "net/http" "go.uber.org/zap" "github.com/yorukot/starker/internal/repository" "github.com/yorukot/starker/internal/service/collectionsvc" "github.com/yorukot/starker/pkg/response" ) // GetCollections godoc // @Summary Get all collections // @Description Gets all collections with their hierarchical structure and associated monitors // @Tags collections // @Accept json // @Produce json // @Success 200 {object} []collectionsvc.CollectionWithDetails "List of collections with their children and monitors" // @Failure 500 {object} response.ErrorResponse "Internal server error" // @Router /collections [get] func (h *CollectionHandler) GetCollections(w http.ResponseWriter, r *http.Request) { // Start the transaction tx, err := repository.StartTransaction(h.DB, r.Context()) if err != nil { zap.L().Error("Failed to begin transaction", zap.Error(err)) response.RespondWithError(w, http.StatusInternalServerError, "Failed to begin transaction", "FAILED_TO_BEGIN_TRANSACTION") return } defer repository.DeferRollback(tx, r.Context()) // Get all collections from the database collections, err := repository.GetAllCollections(r.Context(), tx) if err != nil { zap.L().Error("Failed to get collections", zap.Error(err)) response.RespondWithError(w, http.StatusInternalServerError, "Failed to get collections", "FAILED_TO_GET_COLLECTIONS") return } // Get all monitors from the database monitors, err := repository.GetAllMonitors(r.Context(), tx) if err != nil { zap.L().Error("Failed to get monitors", zap.Error(err)) response.RespondWithError(w, http.StatusInternalServerError, "Failed to get monitors", "FAILED_TO_GET_MONITORS") return } // Build the response structure with collections, their children, and monitors result := collectionsvc.BuildHierarchicalCollections(collections, monitors) // Commit the transaction repository.CommitTransaction(tx, r.Context()) // Return the collections with proper HTTP status and JSON response response.RespondWithJSON(w, http.StatusOK, "Collections retrieved successfully", result) }
yorukot/Houng
1
Go
yorukot
Yorukot
internal/handler/collection/handler.go
Go
package collection import "github.com/jackc/pgx/v5/pgxpool" type CollectionHandler struct { DB *pgxpool.Pool }
yorukot/Houng
1
Go
yorukot
Yorukot
internal/handler/collection/update.go
Go
package collection import ( "encoding/json" "net/http" "time" "github.com/go-chi/chi/v5" "go.uber.org/zap" "github.com/yorukot/starker/internal/repository" "github.com/yorukot/starker/internal/service/collectionsvc" "github.com/yorukot/starker/pkg/response" ) // UpdateCollection godoc // @Summary Update a collection // @Description Updates an existing collection with new name and/or parent collection // @Tags collections // @Accept json // @Produce json // @Param collectionID path string true "Collection ID" // @Param request body collectionsvc.UpdateCollectionRequest true "Update collection request" // @Success 200 {object} models.Collection "Collection updated successfully" // @Failure 400 {object} response.ErrorResponse "Invalid request body or collection not found" // @Failure 500 {object} response.ErrorResponse "Internal server error" // @Router /collections/{collectionID} [patch] func (h *CollectionHandler) UpdateCollection(w http.ResponseWriter, r *http.Request) { // Get the collection ID from the request collectionID := chi.URLParam(r, "collectionID") // Decode the request body var updateRequest collectionsvc.UpdateCollectionRequest if err := json.NewDecoder(r.Body).Decode(&updateRequest); err != nil { response.RespondWithError(w, http.StatusBadRequest, "Invalid request body", "INVALID_REQUEST_BODY") return } // Validate the request body if err := collectionsvc.UpdateCollectionValidate(updateRequest); err != nil { response.RespondWithError(w, http.StatusBadRequest, "Invalid request body", "INVALID_REQUEST_BODY") return } // Start the transaction tx, err := repository.StartTransaction(h.DB, r.Context()) if err != nil { zap.L().Error("Failed to begin transaction", zap.Error(err)) response.RespondWithError(w, http.StatusInternalServerError, "Failed to begin transaction", "FAILED_TO_BEGIN_TRANSACTION") return } defer repository.DeferRollback(tx, r.Context()) // Get the collection from the database and also check if the collection is exists collection, err := repository.GetCollectionByID(r.Context(), tx, collectionID) if err != nil { zap.L().Error("Failed to get collection by ID", zap.Error(err)) response.RespondWithError(w, http.StatusInternalServerError, "Failed to get collection", "FAILED_TO_GET_COLLECTION") return } if collection == nil { response.RespondWithError(w, http.StatusBadRequest, "Collection not found", "COLLECTION_NOT_FOUND") return } // If the parent is exist check if it is exists if *updateRequest.ParentCollectionID != "" { updateRequest.ParentCollectionID = nil } if updateRequest.ParentCollectionID != nil { parentCollection, err := repository.GetCollectionByID(r.Context(), tx, *updateRequest.ParentCollectionID) if err != nil { zap.L().Error("Failed to get parent collection by ID", zap.Error(err)) response.RespondWithError(w, http.StatusInternalServerError, "Failed to get parent collection", "FAILED_TO_GET_PARENT_COLLECTION") return } if parentCollection == nil { response.RespondWithError(w, http.StatusBadRequest, "Parent collection not found", "PARENT_COLLECTION_NOT_FOUND") return } } // Update the collection if updateRequest.Name != nil { collection.Name = *updateRequest.Name } collection.ParentCollectionID = updateRequest.ParentCollectionID collection.UpdatedAt = time.Now() if err = repository.UpdateCollection(r.Context(), tx, *collection); err != nil { zap.L().Error("Failed to update collection", zap.Error(err)) response.RespondWithError(w, http.StatusInternalServerError, "Failed to update collection", "FAILED_TO_UPDATE_COLLECTION") return } // Commit the transaction repository.CommitTransaction(tx, r.Context()) // Return the response with the collection response.RespondWithJSON(w, http.StatusOK, "Collection updated successfully", collection) }
yorukot/Houng
1
Go
yorukot
Yorukot
internal/handler/monitor/create.go
Go
package monitor import ( "encoding/json" "net/http" "strings" "github.com/go-chi/chi/v5" "go.uber.org/zap" "github.com/yorukot/starker/internal/repository" "github.com/yorukot/starker/internal/service/monitorsvc" "github.com/yorukot/starker/pkg/response" ) // +----------------------------------------------+ // | CreateMonitor | // +----------------------------------------------+ // CreateMonitor godoc // @Summary Create a new monitor // @Description Creates a new monitor configuration for the specified node // @Tags monitor // @Accept json // @Produce json // @Param nodeID path string true "Node ID" // @Param request body monitorsvc.CreateMonitorRequest true "Monitor creation request" // @Success 200 {object} models.Monitor "Monitor created successfully" // @Failure 400 {object} response.ErrorResponse "Invalid request body or node not found" // @Failure 500 {object} response.ErrorResponse "Internal server error" // @Router /nodes/monitors/{nodeID} [post] func (h *MonitorHandler) CreateMonitor(w http.ResponseWriter, r *http.Request) { // Get the node ID from the request nodeID := chi.URLParam(r, "nodeID") if nodeID == "" { response.RespondWithError(w, http.StatusBadRequest, "Node ID is required", "NODE_ID_REQUIRED") return } // Decode the request body var createRequest monitorsvc.CreateMonitorRequest if err := json.NewDecoder(r.Body).Decode(&createRequest); err != nil { response.RespondWithError(w, http.StatusBadRequest, "Invalid request body", "INVALID_REQUEST_BODY") return } // Validate the request body if err := monitorsvc.CreateMonitorValidate(createRequest); err != nil { response.RespondWithError(w, http.StatusBadRequest, "Invalid request body", "INVALID_REQUEST_BODY") return } // Start the transaction tx, err := repository.StartTransaction(h.DB, r.Context()) if err != nil { zap.L().Error("Failed to begin transaction", zap.Error(err)) response.RespondWithError(w, http.StatusInternalServerError, "Failed to begin transaction", "FAILED_TO_BEGIN_TRANSACTION") return } defer repository.DeferRollback(tx, r.Context()) // Check if the node exists node, err := repository.GetNodeByID(r.Context(), tx, nodeID) if err != nil { zap.L().Error("Failed to get node by ID", zap.Error(err)) response.RespondWithError(w, http.StatusInternalServerError, "Failed to get node by ID", "FAILED_TO_GET_NODE_BY_ID") return } if node == nil { response.RespondWithError(w, http.StatusBadRequest, "Node not found", "NODE_NOT_FOUND") return } // Check if the collection exists collection, err := repository.GetCollectionByID(r.Context(), tx, createRequest.CollectionID) if err != nil { zap.L().Error("Failed to get collection by ID", zap.Error(err)) response.RespondWithError(w, http.StatusInternalServerError, "Failed to get collection by ID", "FAILED_TO_GET_COLLECTION_BY_ID") return } if collection == nil { response.RespondWithError(w, http.StatusBadRequest, "Collection not found", "COLLECTION_NOT_FOUND") return } // Create the monitor monitor := monitorsvc.GenerateMonitor(createRequest, nodeID) if err = repository.CreateMonitor(r.Context(), tx, monitor); err != nil { zap.L().Error("Failed to create monitor", zap.Error(err)) response.RespondWithError(w, http.StatusInternalServerError, "Failed to create monitor", "FAILED_TO_CREATE_MONITOR") return } // Commit the transaction repository.CommitTransaction(tx, r.Context()) // Return the monitor response.RespondWithJSON(w, http.StatusOK, "Monitor created successfully", monitor) } // +----------------------------------------------+ // | PingMonitor | // +----------------------------------------------+ // PingMonitor godoc // @Summary Execute a ping operation for a monitor // @Description Executes a ping operation for the specified monitor and stores the result // @Tags monitor // @Accept json // @Produce json // @Param monitorID path string true "Monitor ID" // @Param Authorization header string true "Bearer token for node authentication" default(Bearer your-node-token) // @Param request body monitorsvc.PingRequest true "Ping request with timestamp and latency data" // @Success 200 {object} models.Ping "Ping executed successfully" // @Failure 400 {object} response.ErrorResponse "Invalid request or monitor not found" // @Failure 401 {object} response.ErrorResponse "Invalid authentication token" // @Failure 500 {object} response.ErrorResponse "Internal server error" // @Router /monitors/{monitorID}/ping [post] func (h *MonitorHandler) PingMonitor(w http.ResponseWriter, r *http.Request) { // Get the monitor ID from the request URL parameter monitorID := chi.URLParam(r, "monitorID") if monitorID == "" { response.RespondWithError(w, http.StatusBadRequest, "Monitor ID is required", "MONITOR_ID_REQUIRED") return } // Extract Bearer token from Authorization header authHeader := r.Header.Get("Authorization") if authHeader == "" { response.RespondWithError(w, http.StatusUnauthorized, "Authorization header required", "AUTHORIZATION_REQUIRED") return } bearerToken := strings.TrimPrefix(authHeader, "Bearer ") if bearerToken == authHeader { response.RespondWithError(w, http.StatusUnauthorized, "Bearer token required", "BEARER_TOKEN_REQUIRED") return } // Decode the ping request body containing ping data var pingRequest monitorsvc.PingRequest if err := json.NewDecoder(r.Body).Decode(&pingRequest); err != nil { zap.L().Error("Failed to decode ping request", zap.Error(err)) response.RespondWithError(w, http.StatusBadRequest, "Invalid request body", "INVALID_REQUEST_BODY") return } // Validate the ping request data if err := monitorsvc.ValidatePingRequest(pingRequest); err != nil { response.RespondWithError(w, http.StatusBadRequest, "Invalid request body", "INVALID_REQUEST_BODY") return } // Start database transaction for atomic operations tx, err := repository.StartTransaction(h.DB, r.Context()) if err != nil { zap.L().Error("Failed to begin transaction", zap.Error(err)) response.RespondWithError(w, http.StatusInternalServerError, "Failed to begin transaction", "FAILED_TO_BEGIN_TRANSACTION") return } defer repository.DeferRollback(tx, r.Context()) // Get the monitor from the database and verify it exists monitor, err := repository.GetMonitorByID(r.Context(), tx, monitorID) if err != nil { zap.L().Error("Failed to get monitor by ID", zap.Error(err)) response.RespondWithError(w, http.StatusInternalServerError, "Failed to get monitor by ID", "FAILED_TO_GET_MONITOR_BY_ID") return } if monitor == nil { response.RespondWithError(w, http.StatusBadRequest, "Monitor not found", "MONITOR_NOT_FOUND") return } // Get the node that owns this monitor to validate the token node, err := repository.GetNodeByID(r.Context(), tx, monitor.From) if err != nil { zap.L().Error("Failed to get node by ID", zap.Error(err)) response.RespondWithError(w, http.StatusInternalServerError, "Failed to get node by ID", "FAILED_TO_GET_NODE_BY_ID") return } if node == nil { response.RespondWithError(w, http.StatusBadRequest, "Node not found", "NODE_NOT_FOUND") return } // Verify the Bearer token matches the node's authentication token if !monitorsvc.ValidateMonitorToken(node, bearerToken) { zap.L().Warn("Invalid authentication token for monitor", zap.String("monitor_id", monitorID), zap.String("node_id", monitor.From), zap.String("client_ip", r.RemoteAddr)) response.RespondWithError(w, http.StatusUnauthorized, "Invalid authentication token", "INVALID_TOKEN") return } // Generate and create the ping record with the provided data ping := monitorsvc.GeneratePing(monitor, pingRequest) if err = repository.CreatePing(r.Context(), tx, ping); err != nil { zap.L().Error("Failed to create ping record", zap.Error(err)) response.RespondWithError(w, http.StatusInternalServerError, "Failed to create ping record", "FAILED_TO_CREATE_PING") return } // Commit the transaction to persist changes repository.CommitTransaction(tx, r.Context()) // Log successful ping operation zap.L().Info("Ping operation completed successfully", zap.String("monitor_id", monitorID), zap.String("node_id", ping.NodeID), zap.Bool("packet_loss", ping.PacketLoss)) // Return the created ping record response.RespondWithJSON(w, http.StatusOK, "Ping executed successfully", ping) }
yorukot/Houng
1
Go
yorukot
Yorukot
internal/handler/monitor/delete.go
Go
package monitor import "net/http" func (h *MonitorHandler) DeleteMonitor(w http.ResponseWriter, r *http.Request) { // Get the monitor ID from the request // Start the transaction // Check if the monitor is exists // Delete the monitor // Commit the transaction // Return the monitor }
yorukot/Houng
1
Go
yorukot
Yorukot
internal/handler/monitor/get.go
Go
package monitor import ( "net/http" "github.com/go-chi/chi/v5" "go.uber.org/zap" "github.com/yorukot/starker/internal/repository" "github.com/yorukot/starker/pkg/response" ) // +----------------------------------------------+ // | GetMonitor | // +----------------------------------------------+ // GetMonitor godoc // @Summary Get a monitor by ID // @Description Retrieves a specific monitor configuration by its ID // @Tags monitor // @Produce json // @Param monitorID path string true "Monitor ID" // @Success 200 {object} models.Monitor "Monitor retrieved successfully" // @Failure 400 {object} response.ErrorResponse "Monitor ID is required" // @Failure 404 {object} response.ErrorResponse "Monitor not found" // @Failure 500 {object} response.ErrorResponse "Internal server error" // @Router /monitors/{monitorID} [get] func (h *MonitorHandler) GetMonitor(w http.ResponseWriter, r *http.Request) { // Get the monitor ID from the URL parameters monitorID := chi.URLParam(r, "monitorID") if monitorID == "" { response.RespondWithError(w, http.StatusBadRequest, "Monitor ID is required", "MONITOR_ID_REQUIRED") return } // Start a database transaction for consistent reads tx, err := repository.StartTransaction(h.DB, r.Context()) if err != nil { zap.L().Error("Failed to begin transaction", zap.Error(err)) response.RespondWithError(w, http.StatusInternalServerError, "Failed to begin transaction", "FAILED_TO_BEGIN_TRANSACTION") return } defer repository.DeferRollback(tx, r.Context()) // Get the monitor from the database and check if it exists monitor, err := repository.GetMonitorByID(r.Context(), tx, monitorID) if err != nil { zap.L().Error("Failed to get monitor by ID", zap.String("monitorID", monitorID), zap.Error(err)) response.RespondWithError(w, http.StatusInternalServerError, "Failed to get monitor by ID", "FAILED_TO_GET_MONITOR_BY_ID") return } // Check if the monitor exists if monitor == nil { response.RespondWithError(w, http.StatusNotFound, "Monitor not found", "MONITOR_NOT_FOUND") return } // Commit the transaction repository.CommitTransaction(tx, r.Context()) // Return the monitor as JSON response response.RespondWithJSON(w, http.StatusOK, "Monitor retrieved successfully", monitor) }
yorukot/Houng
1
Go
yorukot
Yorukot
internal/handler/monitor/handler.go
Go
package monitor import ( "github.com/jackc/pgx/v5/pgxpool" ) type MonitorHandler struct { DB *pgxpool.Pool }
yorukot/Houng
1
Go
yorukot
Yorukot
internal/handler/monitor/update.go
Go
package monitor import ( "encoding/json" "net/http" "github.com/go-chi/chi/v5" "go.uber.org/zap" "github.com/yorukot/starker/internal/repository" "github.com/yorukot/starker/internal/service/monitorsvc" "github.com/yorukot/starker/pkg/response" ) // +----------------------------------------------+ // | UpdateMonitor | // +----------------------------------------------+ // UpdateMonitor godoc // @Summary Update an existing monitor // @Description Updates an existing monitor configuration by its ID // @Tags monitor // @Accept json // @Produce json // @Param monitorID path string true "Monitor ID" // @Param request body monitorsvc.UpdateMonitorRequest true "Monitor update request" // @Success 200 {object} models.Monitor "Monitor updated successfully" // @Failure 400 {object} response.ErrorResponse "Invalid request body or monitor/collection not found" // @Failure 404 {object} response.ErrorResponse "Monitor not found" // @Failure 500 {object} response.ErrorResponse "Internal server error" // @Router /monitors/{monitorID} [put] func (h *MonitorHandler) UpdateMonitor(w http.ResponseWriter, r *http.Request) { // Extract the monitor ID from the URL path parameters monitorID := chi.URLParam(r, "monitorID") if monitorID == "" { response.RespondWithError(w, http.StatusBadRequest, "Monitor ID is required", "MONITOR_ID_REQUIRED") return } // Decode and validate the JSON request body containing monitor updates var updateRequest monitorsvc.UpdateMonitorRequest if err := json.NewDecoder(r.Body).Decode(&updateRequest); err != nil { response.RespondWithError(w, http.StatusBadRequest, "Invalid request body", "INVALID_REQUEST_BODY") return } // Validate the decoded request structure and field constraints if err := monitorsvc.UpdateMonitorValidate(updateRequest); err != nil { response.RespondWithError(w, http.StatusBadRequest, "Invalid request body", "INVALID_REQUEST_BODY") return } // Begin database transaction to ensure data consistency across operations tx, err := repository.StartTransaction(h.DB, r.Context()) if err != nil { zap.L().Error("Failed to begin transaction", zap.Error(err)) response.RespondWithError(w, http.StatusInternalServerError, "Failed to begin transaction", "FAILED_TO_BEGIN_TRANSACTION") return } defer repository.DeferRollback(tx, r.Context()) // Verify that the monitor exists in the database before attempting update existingMonitor, err := repository.GetMonitorByID(r.Context(), tx, monitorID) if err != nil { zap.L().Error("Failed to get monitor by ID", zap.Error(err)) response.RespondWithError(w, http.StatusInternalServerError, "Failed to get monitor by ID", "FAILED_TO_GET_MONITOR_BY_ID") return } if existingMonitor == nil { response.RespondWithError(w, http.StatusNotFound, "Monitor not found", "MONITOR_NOT_FOUND") return } // Verify that the collection exists if collection ID is being updated if updateRequest.CollectionID != nil { collection, err := repository.GetCollectionByID(r.Context(), tx, *updateRequest.CollectionID) if err != nil { zap.L().Error("Failed to get collection by ID", zap.Error(err)) response.RespondWithError(w, http.StatusInternalServerError, "Failed to get collection by ID", "FAILED_TO_GET_COLLECTION_BY_ID") return } if collection == nil { response.RespondWithError(w, http.StatusBadRequest, "Collection not found", "COLLECTION_NOT_FOUND") return } } // Apply the updates to the existing monitor and persist changes to database updatedMonitor := monitorsvc.ApplyMonitorUpdates(*existingMonitor, updateRequest) if err = repository.UpdateMonitor(r.Context(), tx, updatedMonitor); err != nil { zap.L().Error("Failed to update monitor", zap.Error(err)) response.RespondWithError(w, http.StatusInternalServerError, "Failed to update monitor", "FAILED_TO_UPDATE_MONITOR") return } // Commit the transaction to make all changes permanent repository.CommitTransaction(tx, r.Context()) // Return the updated monitor configuration to the client response.RespondWithJSON(w, http.StatusOK, "Monitor updated successfully", updatedMonitor) }
yorukot/Houng
1
Go
yorukot
Yorukot
internal/handler/node/create.go
Go
package node import ( "encoding/json" "net/http" "go.uber.org/zap" "github.com/yorukot/starker/internal/repository" "github.com/yorukot/starker/internal/service/nodesvc" "github.com/yorukot/starker/pkg/response" ) // CreateNode godoc // @Summary Create a new node // @Description Creates a new infrastructure node with IP and optional name // @Tags nodes // @Accept json // @Produce json // @Param request body nodesvc.CreateNodeRequest true "Node creation request" // @Success 200 {object} models.Node "Node created successfully" // @Failure 400 {object} response.ErrorResponse "Invalid request body or IP already in use" // @Failure 500 {object} response.ErrorResponse "Internal server error" // @Router /nodes [post] func (h *NodeHandler) CreateNode(w http.ResponseWriter, r *http.Request) { // Validate the request body var createNodeRequest nodesvc.CreateNodeRequest if err := json.NewDecoder(r.Body).Decode(&createNodeRequest); err != nil { response.RespondWithError(w, http.StatusBadRequest, "Invalid request body", "INVALID_REQUEST_BODY") return } // Validate the request body if err := nodesvc.CreateNodeValidate(createNodeRequest); err != nil { response.RespondWithError(w, http.StatusBadRequest, "Invalid request body", "INVALID_REQUEST_BODY") return } // Begin the transaction tx, err := repository.StartTransaction(h.DB, r.Context()) if err != nil { zap.L().Error("Failed to begin transaction", zap.Error(err)) response.RespondWithError(w, http.StatusInternalServerError, "Failed to begin transaction", "FAILED_TO_BEGIN_TRANSACTION") return } defer repository.DeferRollback(tx, r.Context()) // Check if node with this IP already exists existingNode, err := repository.GetNodeByIP(r.Context(), tx, createNodeRequest.IP) if err != nil { zap.L().Error("Failed to check if node exists", zap.Error(err)) response.RespondWithError(w, http.StatusInternalServerError, "Failed to check if node exists", "FAILED_TO_CHECK_IF_NODE_EXISTS") return } if existingNode != nil { response.RespondWithError(w, http.StatusBadRequest, "Node with this IP already exists", "NODE_IP_ALREADY_EXISTS") return } // Generate the node schema node, err := nodesvc.GenerateNode(createNodeRequest) if err != nil { zap.L().Error("Failed to generate node", zap.Error(err)) response.RespondWithError(w, http.StatusInternalServerError, "Failed to generate node", "FAILED_TO_GENERATE_NODE") return } // Save the node to the database if err = repository.CreateNode(r.Context(), tx, node); err != nil { zap.L().Error("Failed to create node", zap.Error(err)) response.RespondWithError(w, http.StatusInternalServerError, "Failed to create node", "FAILED_TO_CREATE_NODE") return } // Commit the transaction repository.CommitTransaction(tx, r.Context()) // Return the nodes response.RespondWithJSON(w, http.StatusOK, "Node created successfully", node) }
yorukot/Houng
1
Go
yorukot
Yorukot
internal/handler/node/delete.go
Go
package node import ( "net/http" "github.com/go-chi/chi/v5" "go.uber.org/zap" "github.com/yorukot/starker/internal/repository" "github.com/yorukot/starker/pkg/response" ) // DeleteNode godoc // @Summary Delete a node // @Description Deletes a node by ID. Node cannot be deleted if it has associated monitors // @Tags nodes // @Accept json // @Produce json // @Param nodeID path string true "Node ID" // @Success 200 {object} string "Node deleted successfully" // @Failure 400 {object} response.ErrorResponse "Invalid node ID or node has associated monitors" // @Failure 404 {object} response.ErrorResponse "Node not found" // @Failure 500 {object} response.ErrorResponse "Internal server error" // @Router /nodes/{nodeID} [delete] func (h *NodeHandler) DeleteNode(w http.ResponseWriter, r *http.Request) { // Get the node ID from the request nodeID := chi.URLParam(r, "nodeID") if nodeID == "" { response.RespondWithError(w, http.StatusBadRequest, "Node ID is required", "NODE_ID_REQUIRED") return } // Start the transaction tx, err := repository.StartTransaction(h.DB, r.Context()) if err != nil { zap.L().Error("Failed to begin transaction", zap.Error(err)) response.RespondWithError(w, http.StatusInternalServerError, "Failed to begin transaction", "FAILED_TO_BEGIN_TRANSACTION") return } defer repository.DeferRollback(tx, r.Context()) // Check if the node exists existingNode, err := repository.GetNodeByID(r.Context(), tx, nodeID) if err != nil { zap.L().Error("Failed to get node by ID", zap.Error(err)) response.RespondWithError(w, http.StatusInternalServerError, "Failed to get node by ID", "FAILED_TO_GET_NODE_BY_ID") return } if existingNode == nil { response.RespondWithError(w, http.StatusNotFound, "Node not found", "NODE_NOT_FOUND") return } // Check if node has associated monitors monitors, err := repository.GetMonitorsByNodeID(r.Context(), tx, nodeID) if err != nil { zap.L().Error("Failed to check node monitors", zap.Error(err)) response.RespondWithError(w, http.StatusInternalServerError, "Failed to check node monitors", "FAILED_TO_CHECK_NODE_MONITORS") return } if len(monitors) > 0 { response.RespondWithError(w, http.StatusBadRequest, "Cannot delete node with associated monitors", "NODE_HAS_MONITORS") return } // Delete the node if err = repository.DeleteNode(r.Context(), tx, nodeID); err != nil { zap.L().Error("Failed to delete node", zap.Error(err)) response.RespondWithError(w, http.StatusInternalServerError, "Failed to delete node", "FAILED_TO_DELETE_NODE") return } // Commit the transaction repository.CommitTransaction(tx, r.Context()) // Return the response response.RespondWithJSON(w, http.StatusOK, "Node deleted successfully", nil) }
yorukot/Houng
1
Go
yorukot
Yorukot
internal/handler/node/get.go
Go
package node import ( "net/http" "github.com/yorukot/starker/internal/repository" "github.com/yorukot/starker/pkg/response" ) // GetNodes godoc // @Summary Get all nodes // @Description Get all nodes // @Tags nodes // @Accept json // @Produce json // @Success 200 {array} models.Node "Nodes fetched successfully" // @Failure 500 {object} response.ErrorResponse "Internal server error" // @Router /nodes [get] func (h *NodeHandler) GetNodes(w http.ResponseWriter, r *http.Request) { // Begin the transaction tx, err := repository.StartTransaction(h.DB, r.Context()) if err != nil { response.RespondWithError(w, http.StatusInternalServerError, "Failed to begin transaction", "FAILED_TO_BEGIN_TRANSACTION") return } defer repository.DeferRollback(tx, r.Context()) // Get the nodes from the database nodes, err := repository.GetNodes(r.Context(), tx) if err != nil { response.RespondWithError(w, http.StatusInternalServerError, "Failed to get nodes", "FAILED_TO_GET_NODES") return } // Commit the transaction if err := tx.Commit(r.Context()); err != nil { response.RespondWithError(w, http.StatusInternalServerError, "Failed to commit transaction", "FAILED_TO_COMMIT_TRANSACTION") return } // Return the nodes response.RespondWithJSON(w, http.StatusOK, "Nodes fetched successfully", nodes) }
yorukot/Houng
1
Go
yorukot
Yorukot
internal/handler/node/handler.go
Go
package node import "github.com/jackc/pgx/v5/pgxpool" type NodeHandler struct { DB *pgxpool.Pool }
yorukot/Houng
1
Go
yorukot
Yorukot
internal/handler/node/update.go
Go
package node import ( "encoding/json" "net/http" "time" "github.com/go-chi/chi/v5" "go.uber.org/zap" "github.com/yorukot/starker/internal/repository" "github.com/yorukot/starker/internal/service/nodesvc" "github.com/yorukot/starker/pkg/response" ) // UpdateNode godoc // @Summary Update a node // @Description Updates a node's information (currently only name) // @Tags nodes // @Accept json // @Produce json // @Param nodeID path string true "Node ID" // @Param request body nodesvc.UpdateNodeRequest true "Node update request" // @Success 200 {object} models.Node "Node updated successfully" // @Failure 400 {object} response.ErrorResponse "Invalid request body or node ID" // @Failure 404 {object} response.ErrorResponse "Node not found" // @Failure 500 {object} response.ErrorResponse "Internal server error" // @Router /nodes/{nodeID} [patch] func (h *NodeHandler) UpdateNode(w http.ResponseWriter, r *http.Request) { // Get the node ID from the request nodeID := chi.URLParam(r, "nodeID") if nodeID == "" { response.RespondWithError(w, http.StatusBadRequest, "Node ID is required", "NODE_ID_REQUIRED") return } // Validate the request body (Right now the user can only update the name) var updateNodeRequest nodesvc.UpdateNodeRequest if err := json.NewDecoder(r.Body).Decode(&updateNodeRequest); err != nil { response.RespondWithError(w, http.StatusBadRequest, "Invalid request body", "INVALID_REQUEST_BODY") return } // Validate the request body if err := nodesvc.UpdateNodeValidate(updateNodeRequest); err != nil { response.RespondWithError(w, http.StatusBadRequest, "Invalid request body", "INVALID_REQUEST_BODY") return } // Start the transaction tx, err := repository.StartTransaction(h.DB, r.Context()) if err != nil { zap.L().Error("Failed to begin transaction", zap.Error(err)) response.RespondWithError(w, http.StatusInternalServerError, "Failed to begin transaction", "FAILED_TO_BEGIN_TRANSACTION") return } defer repository.DeferRollback(tx, r.Context()) // Check if the node exists existingNode, err := repository.GetNodeByID(r.Context(), tx, nodeID) if err != nil { zap.L().Error("Failed to get node by ID", zap.Error(err)) response.RespondWithError(w, http.StatusInternalServerError, "Failed to get node by ID", "FAILED_TO_GET_NODE_BY_ID") return } if existingNode == nil { response.RespondWithError(w, http.StatusNotFound, "Node not found", "NODE_NOT_FOUND") return } // Update the node existingNode.Name = updateNodeRequest.Name existingNode.UpdatedAt = time.Now() if err = repository.UpdateNode(r.Context(), tx, *existingNode); err != nil { zap.L().Error("Failed to update node", zap.Error(err)) response.RespondWithError(w, http.StatusInternalServerError, "Failed to update node", "FAILED_TO_UPDATE_NODE") return } // Commit the transaction repository.CommitTransaction(tx, r.Context()) // Return the node response.RespondWithJSON(w, http.StatusOK, "Node updated successfully", existingNode) }
yorukot/Houng
1
Go
yorukot
Yorukot
internal/handler/type.go
Go
package handler import "github.com/jackc/pgx/v5/pgxpool" // App is the application context type App struct { DB *pgxpool.Pool }
yorukot/Houng
1
Go
yorukot
Yorukot
internal/middleware/auth.go
Go
package middleware import ( "context" "net/http" "github.com/yorukot/starker/internal/config" "github.com/yorukot/starker/internal/models" "github.com/yorukot/starker/pkg/encrypt" "github.com/yorukot/starker/pkg/response" ) // authMiddlewareLogic is the logic for the auth middleware func authMiddlewareLogic(w http.ResponseWriter, token string) (bool, *encrypt.AccessTokenClaims, error) { JWTSecret := encrypt.JWTSecret{ Secret: config.Env().JWTSecretKey, } valid, claims, err := JWTSecret.ValidateAccessTokenAndGetClaims(token) if err != nil { response.RespondWithError(w, http.StatusInternalServerError, "Internal server error", "INTERNAL_SERVER_ERROR") return false, nil, err } if !valid { response.RespondWithError(w, http.StatusUnauthorized, "Invalid token", "INVALID_TOKEN") return false, nil, nil } return true, &claims, nil } // AuthRequiredMiddleware is the middleware for the auth required func AuthRequiredMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { cookie, err := r.Cookie(models.CookieNameAccessToken) if err != nil { response.RespondWithError(w, http.StatusUnauthorized, "Unauthorized", "UNAUTHORIZED") return } valid, claims, err := authMiddlewareLogic(w, cookie.Value) if err != nil || !valid { return } ctx := context.WithValue(r.Context(), UserIDKey, claims.Subject) next.ServeHTTP(w, r.WithContext(ctx)) }) }
yorukot/Houng
1
Go
yorukot
Yorukot
internal/middleware/logger.go
Go
package middleware import ( "net/http" "time" "github.com/fatih/color" "github.com/google/uuid" "go.uber.org/zap" "github.com/yorukot/starker/internal/config" ) // ZapLoggerMiddleware is a middleware that logs the incoming request and the response time func ZapLoggerMiddleware(logger *zap.Logger) func(http.Handler) http.Handler { return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { requestID := uuid.New().String() start := time.Now() next.ServeHTTP(w, r) logger.Info(GenerateDiffrentColorForMethod(r.Method)+" request completed", zap.String("request_id", requestID), zap.String("path", r.URL.Path), zap.String("user_agent", r.UserAgent()), zap.String("remote_addr", r.RemoteAddr), zap.Duration("duration", time.Since(start)), ) }) } } // GenerateDiffrentColorForMethod generate a different color for the method func GenerateDiffrentColorForMethod(method string) string { if config.Env().AppEnv == config.AppEnvDev { switch method { case "GET": return color.GreenString(method) case "POST": return color.BlueString(method) case "PUT": return color.YellowString(method) case "PATCH": return color.MagentaString(method) case "DELETE": return color.RedString(method) case "OPTIONS": return color.CyanString(method) case "HEAD": return color.WhiteString(method) default: return method } } return method }
yorukot/Houng
1
Go
yorukot
Yorukot
internal/middleware/type.go
Go
package middleware // ContextKey is a type for the context key type ContextKey string // ContextKey constants const ( UserIDKey ContextKey = "userID" )
yorukot/Houng
1
Go
yorukot
Yorukot
internal/models/auth.go
Go
package models // CookieName constants const ( CookieNameAccessToken = "access_token" )
yorukot/Houng
1
Go
yorukot
Yorukot
internal/models/collection.go
Go
package models import "time" // Collection represents a hierarchical collection in the system type Collection struct { ID string `json:"id" example:"01ARZ3NDEKTSV4RRFFQ69G5FAV"` // Unique identifier for the collection Name string `json:"name" example:"Production Servers"` // Name of the collection ParentCollectionID *string `json:"parent_collection_id,omitempty" example:"01ARZ3NDEKTSV4RRFFQ"` // Optional parent collection ID for hierarchy UpdatedAt time.Time `json:"updated_at" example:"2023-01-01T12:00:00Z"` // Timestamp when the collection was last updated CreatedAt time.Time `json:"created_at" example:"2023-01-01T12:00:00Z"` // Timestamp when the collection was created }
yorukot/Houng
1
Go
yorukot
Yorukot
internal/models/monitor.go
Go
package models import "time" // Monitor represents a monitoring configuration in the system type Monitor struct { ID string `json:"id" example:"01ARZ3NDEKTSV4RRFFQ69G5FAV"` // Unique identifier for the monitor CollectionID string `json:"collection_id" example:"01ARZ3NDEKTSV4RRFFQ"` // ID of the collection this monitor belongs to From string `json:"from" example:"01ARZ3NDEKTSV4RRFFQ69G5FAV"` // ID of the node performing the monitoring Name string `json:"name" example:"Web Server Health Check"` // Name of the monitoring configuration ToIP string `json:"to_ip" example:"192.168.1.200"` // Target IP address to monitor ToName *string `json:"to_name,omitempty" example:"web-server-02"` // Optional name for the target UpdatedAt time.Time `json:"updated_at" example:"2023-01-01T12:00:00Z"` // Timestamp when the monitor was last updated CreatedAt time.Time `json:"created_at" example:"2023-01-01T12:00:00Z"` // Timestamp when the monitor was created }
yorukot/Houng
1
Go
yorukot
Yorukot
internal/models/node.go
Go
package models import "time" // Node represents an infrastructure node in the system type Node struct { ID string `json:"id" example:"01ARZ3NDEKTSV4RRFFQ69G5FAV"` // Unique identifier for the node IP string `json:"ip" example:"192.168.1.100"` // IP address of the node Name *string `json:"name,omitempty" example:"web-server-01"` // Optional name for the node Token string `json:"token" example:"node_auth_token_123"` // Authentication token for the node UpdatedAt time.Time `json:"updated_at" example:"2023-01-01T12:00:00Z"` // Timestamp when the node was last updated CreatedAt time.Time `json:"created_at" example:"2023-01-01T12:00:00Z"` // Timestamp when the node was created }
yorukot/Houng
1
Go
yorukot
Yorukot
internal/models/ping.go
Go
package models import "time" // Ping represents a ping result in the system type Ping struct { PingID string `json:"ping_id" example:"01ARZ3NDEKTSV4RRFFQ69G5FAV"` // Unique identifier for the ping NodeID string `json:"node_id" example:"01ARZ3NDEKTSV4RRFFQ69G5FAV"` // ID of the node that performed the ping Time time.Time `json:"time" example:"2023-01-01T12:00:00Z"` // Timestamp when the ping was performed LatencyMs *float32 `json:"latency_ms,omitempty" example:"25.5"` // Response time in milliseconds (nullable) PacketLoss bool `json:"packet_loss" example:"false"` // Whether the ping resulted in packet loss }
yorukot/Houng
1
Go
yorukot
Yorukot
internal/repository/collection.go
Go
package repository import ( "context" "github.com/jackc/pgx/v5" "github.com/yorukot/starker/internal/models" ) // GetCollectionByID gets a collection by ID func GetCollectionByID(ctx context.Context, tx pgx.Tx, id string) (*models.Collection, error) { query := ` SELECT id, name, parent_collection_id, created_at, updated_at FROM collections WHERE id = $1 ` var collection models.Collection err := tx.QueryRow(ctx, query, id).Scan( &collection.ID, &collection.Name, &collection.ParentCollectionID, &collection.CreatedAt, &collection.UpdatedAt, ) if err != nil { if err == pgx.ErrNoRows { return nil, nil } return nil, err } return &collection, nil } // GetAllCollections gets all collections from the database func GetAllCollections(ctx context.Context, tx pgx.Tx) ([]models.Collection, error) { query := ` SELECT id, name, parent_collection_id, created_at, updated_at FROM collections ORDER BY name ` rows, err := tx.Query(ctx, query) if err != nil { return nil, err } defer rows.Close() var collections []models.Collection for rows.Next() { var collection models.Collection err := rows.Scan( &collection.ID, &collection.Name, &collection.ParentCollectionID, &collection.CreatedAt, &collection.UpdatedAt, ) if err != nil { return nil, err } collections = append(collections, collection) } return collections, nil } // GetCollectionsByParentID gets all collections that have the specified parent collection ID func GetCollectionsByParentID(ctx context.Context, tx pgx.Tx, parentID string) ([]models.Collection, error) { query := ` SELECT id, name, parent_collection_id, created_at, updated_at FROM collections WHERE parent_collection_id = $1 ORDER BY name ` rows, err := tx.Query(ctx, query, parentID) if err != nil { return nil, err } defer rows.Close() var collections []models.Collection for rows.Next() { var collection models.Collection err := rows.Scan( &collection.ID, &collection.Name, &collection.ParentCollectionID, &collection.CreatedAt, &collection.UpdatedAt, ) if err != nil { return nil, err } collections = append(collections, collection) } return collections, nil } // CreateCollection creates a new collection in the database func CreateCollection(ctx context.Context, tx pgx.Tx, collection models.Collection) error { query := ` INSERT INTO collections (id, name, parent_collection_id, created_at, updated_at) VALUES ($1, $2, $3, $4, $5) ` _, err := tx.Exec(ctx, query, collection.ID, collection.Name, collection.ParentCollectionID, collection.CreatedAt, collection.UpdatedAt, ) return err } // UpdateCollection updates a collection in the database func UpdateCollection(ctx context.Context, tx pgx.Tx, collection models.Collection) error { query := ` UPDATE collections SET name = $2, parent_collection_id = $3, updated_at = $4 WHERE id = $1 ` _, err := tx.Exec(ctx, query, collection.ID, collection.Name, collection.ParentCollectionID, collection.UpdatedAt, ) return err } // DeleteCollectionByID deletes a collection by ID func DeleteCollectionByID(ctx context.Context, tx pgx.Tx, id string) error { query := `DELETE FROM collections WHERE id = $1` _, err := tx.Exec(ctx, query, id) return err }
yorukot/Houng
1
Go
yorukot
Yorukot