Files
Lyrebird/Sources/LyrebirdUI/LyrebirdNodeTreeView.swift
T
2026-06-01 18:27:40 -07:00

265 lines
8.2 KiB
Swift

// LyrebirdNodeTreeView.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import SwiftUI
import LyrebirdSynth
/// Live tree view of the engine's `NodeTreeMirror`.
///
/// Renders rows head→tail (top-to-bottom reading order matches RT signal
/// flow). Groups expand / collapse via `DisclosureGroup`. Each row shows
/// a kind glyph, a class name, an optional 4-hex identity suffix, and a
/// child-count badge for groups.
///
/// ## Hosting
///
/// Embed inside any SwiftUI parent:
///
/// ```swift
/// LyrebirdNodeTreeView(engine: engine)
/// .padding()
/// ```
///
/// On macOS, `presentInWindow(...)` opens a detached `LyrebirdWindow`.
///
/// ## Threading
///
/// `NodeTreeMirror` and its `snapshot` are read on the main thread. SwiftUI
/// view bodies run on the main thread; reads are safe.
public struct LyrebirdNodeTreeView: View {
/// `@Observable` reference; SwiftUI tracks `snapshot` reads via the
/// macro-synthesized observation registrar.
private let mirror: NodeTreeMirror
@State private var expanded: Set<ObjectIdentifier> = []
/// Creates a node-tree view bound to the given engine's mirror.
public init(engine: SynthesisEngine) {
self.mirror = engine.nodeTreeMirror
}
/// Creates a node-tree view bound to the given mirror.
public init(mirror: NodeTreeMirror) {
self.mirror = mirror
}
public var body: some View {
VStack(alignment: .leading, spacing: 6) {
headerRow
Divider()
ScrollView {
VStack(alignment: .leading, spacing: 2) {
NodeRowList(
node: mirror.snapshot.root,
depth: 0,
expanded: $expanded
)
}
.padding(.vertical, 4)
.frame(maxWidth: .infinity, alignment: .leading)
}
}
.padding(12)
.background(Color.lyrebirdControlBackground)
.frame(minWidth: 320, minHeight: 220)
.onAppear { _seedDefaultExpansion() }
}
private var headerRow: some View {
HStack(spacing: 8) {
Text("Node Tree")
.font(.headline)
Spacer()
Button("Expand All") { _expandAll() }
.font(.caption)
Button("Collapse All") { expanded.removeAll() }
.font(.caption)
}
}
/// Default expansion: root + mainGroup open, deeper nodes collapsed.
private func _seedDefaultExpansion() {
guard expanded.isEmpty else { return }
let root: NodeTreeSnapshot.Node = mirror.snapshot.root
expanded.insert(root.id)
for child: NodeTreeSnapshot.Node in root.children where _isContainer(child.kind) {
expanded.insert(child.id)
}
}
private func _expandAll() {
var ids: Set<ObjectIdentifier> = []
_collectContainerIds(mirror.snapshot.root, into: &ids)
expanded = ids
}
private func _collectContainerIds(
_ node: NodeTreeSnapshot.Node,
into ids: inout Set<ObjectIdentifier>
) {
if _isContainer(node.kind) {
ids.insert(node.id)
}
for child: NodeTreeSnapshot.Node in node.children {
_collectContainerIds(child, into: &ids)
}
}
private func _isContainer(_ kind: NodeTreeSnapshot.Node.Kind) -> Bool {
switch kind {
case .group, .parallelGroup: return true
case .synth: return false
}
}
}
// MARK: - Recursive row list
private struct NodeRowList: View {
let node: NodeTreeSnapshot.Node
let depth: Int
@Binding var expanded: Set<ObjectIdentifier>
var body: some View {
let isContainer: Bool = _isContainer(node.kind)
let isExpanded: Bool = expanded.contains(node.id)
NodeRow(
node: node,
depth: depth,
isContainer: isContainer,
isExpanded: isExpanded,
toggle: {
if isExpanded { expanded.remove(node.id) }
else { expanded.insert(node.id) }
}
)
if isContainer && isExpanded {
ForEach(node.children) { child in
NodeRowList(
node: child,
depth: depth + 1,
expanded: $expanded
)
}
}
}
private func _isContainer(_ kind: NodeTreeSnapshot.Node.Kind) -> Bool {
switch kind {
case .group, .parallelGroup: return true
case .synth: return false
}
}
}
// MARK: - Single row
private struct NodeRow: View {
let node: NodeTreeSnapshot.Node
let depth: Int
let isContainer: Bool
let isExpanded: Bool
let toggle: () -> Void
private static let indentPoints: CGFloat = 14
private static let dotIconSize: CGFloat = 6
private static let chevronWidth: CGFloat = 12
private static let identityHexSuffixLen: Int = 4
var body: some View {
HStack(alignment: .firstTextBaseline, spacing: 6) {
Spacer()
.frame(width: CGFloat(depth) * NodeRow.indentPoints)
if isContainer {
Button(action: toggle) {
Image(systemName: isExpanded ? "chevron.down" : "chevron.right")
.font(.caption2)
.foregroundStyle(.secondary)
.frame(width: NodeRow.chevronWidth, alignment: .center)
}
.buttonStyle(.plain)
} else {
Image(systemName: "circle.fill")
.font(.system(size: NodeRow.dotIconSize))
.foregroundStyle(.tertiary)
.frame(width: NodeRow.chevronWidth, alignment: .center)
}
Text(node.displayName)
.font(.callout.monospaced())
.foregroundStyle(.primary)
if let badge: String = childCountBadge {
Text(badge)
.font(.caption2.monospaced())
.foregroundStyle(.secondary)
}
Text(_identityShort(node.id))
.font(.caption2.monospaced())
.foregroundStyle(.tertiary)
Spacer(minLength: 0)
}
.contentShape(Rectangle())
.onTapGesture { if isContainer { toggle() } }
}
private var childCountBadge: String? {
guard isContainer else { return nil }
return "(\(node.children.count))"
}
private func _identityShort(_ id: ObjectIdentifier) -> String {
// Use `hashValue` rather than parsing `String(describing:)`. The
// textual form of `ObjectIdentifier` is a stdlib implementation
// detail with no API guarantee; `hashValue` is process-stable for
// a given object identity (Hashable conformance) and yields a
// deterministic short hex disambiguator.
let mask: Int = (1 << (NodeRow.identityHexSuffixLen * 4)) - 1
let masked: Int = id.hashValue & mask
let raw: String = String(masked, radix: 16, uppercase: false)
let padded: String
if raw.count < NodeRow.identityHexSuffixLen {
padded = String(repeating: "0", count: NodeRow.identityHexSuffixLen - raw.count) + raw
} else {
padded = raw
}
return "#" + padded
}
}
// MARK: - Standalone window (macOS)
#if os(macOS)
extension LyrebirdNodeTreeView {
/// Opens a `LyrebirdWindow` hosting a node-tree view.
///
/// - Parameters:
/// - engine: The engine to mirror.
/// - title: Window title bar text. Defaults to `"Node Tree"`.
/// - width: Initial width in points. Defaults to `420`.
/// - height: Initial height in points. Defaults to `420`.
@MainActor
@discardableResult
public static func presentInWindow(
engine: SynthesisEngine,
title: String = "Node Tree",
width: CGFloat = 420,
height: CGFloat = 420
) -> LyrebirdWindow {
let win: LyrebirdWindow = LyrebirdWindow(title: title, width: width, height: height)
win.open {
LyrebirdNodeTreeView(engine: engine)
}
return win
}
}
#endif