Sources/FaceMaker/VectorEditor.swift
Swift source for Making faces, 118 lines. Raw file
import AppKit
import SwiftUI
/// A face's latent, passed to the read-only vector viewer window.
struct VectorPayload: Identifiable, Hashable, Codable {
let id: Int
let title: String
let values: [Float]
}
/// Editable 512-slider view over the current model's vector. Edits write back
/// live and re-generate the grid (debounced), so the base face updates as you
/// drag. Opened from the Vector blob's "Edit…" button.
struct VectorEditorView: View {
@Environment(AppModel.self) private var model
var body: some View {
VStack(spacing: 0) {
HStack {
Text("Vector — \(model.selectedModel.name)")
.font(.headline)
Spacer()
Button("From seed") { model.resetVectorToSeed() }
.controlSize(.small)
}
.padding(.horizontal, 14)
.padding(.vertical, 10)
Divider()
ScrollView {
LazyVStack(alignment: .leading, spacing: 4) {
ForEach(0..<512, id: \.self) { index in
row(index)
}
}
.padding(.horizontal, 14)
.padding(.vertical, 10)
}
}
.frame(minWidth: 380, minHeight: 460)
.navigationTitle("Vector")
}
private func row(_ index: Int) -> some View {
HStack(spacing: 10) {
Text("\(index)")
.font(.caption.monospacedDigit())
.foregroundStyle(.secondary)
.frame(width: 34, alignment: .trailing)
Slider(value: binding(index), in: -3...3)
NumberField(value: binding(index))
}
}
private func componentValue(_ index: Int) -> Float {
let vector = model.vector
return index < vector.count ? vector[index] : 0
}
private func binding(_ index: Int) -> Binding<Double> {
Binding(
get: { Double(componentValue(index)) },
set: { newValue in
var vector = model.vector
guard index < vector.count else { return }
vector[index] = Float(newValue)
model.vector = vector
})
}
}
/// Read-only listing of one face's exact latent, opened from the viewer's
/// "View Vector" button.
struct VectorViewerView: View {
let payload: VectorPayload
var body: some View {
VStack(spacing: 0) {
HStack {
Text(payload.title).font(.headline)
Spacer()
Button("Copy") {
NSPasteboard.general.clearContents()
NSPasteboard.general.setString(
payload.values.map { String(format: "%.6f", $0) }
.joined(separator: "\n"),
forType: .string)
}
.controlSize(.small)
}
.padding(.horizontal, 14)
.padding(.vertical, 10)
Divider()
ScrollView {
LazyVStack(alignment: .leading, spacing: 3) {
ForEach(Array(payload.values.enumerated()), id: \.offset) { index, value in
HStack(spacing: 10) {
Text("\(index)")
.foregroundStyle(.secondary)
.frame(width: 34, alignment: .trailing)
Text(String(format: "%+.4f", value))
Spacer()
}
.font(.caption.monospacedDigit())
}
}
.padding(.horizontal, 14)
.padding(.vertical, 10)
.textSelection(.enabled)
}
}
.frame(minWidth: 240, minHeight: 420)
.navigationTitle(payload.title)
}
}