Sources/FaceMaker/Persistence.swift
Swift source for Making faces, 54 lines. Raw file
import AppKit
import SwiftUI
/// Persists the host window's frame across launches via AppKit's frame
/// autosave, which SwiftUI's `Window` scene doesn't always restore reliably.
struct WindowFrameAutosave: NSViewRepresentable {
let name: String
func makeNSView(context: Context) -> NSView {
let view = NSView()
DispatchQueue.main.async { [weak view] in
view?.window?.setFrameAutosaveName(name)
}
return view
}
func updateNSView(_ nsView: NSView, context: Context) {}
}
extension View {
func persistWindowFrame(_ name: String) -> some View {
background(WindowFrameAutosave(name: name))
}
/// Persists the position of the enclosing `VSplitView`'s divider by
/// setting the underlying `NSSplitView`'s autosave name. Place inside one
/// of the split's panes.
func persistSplitPosition(_ name: String) -> some View {
background(SplitViewAutosave(name: name))
}
}
/// Finds the enclosing `NSSplitView` (the one SwiftUI's `VSplitView` builds)
/// and gives it an autosave name so its divider position is remembered.
struct SplitViewAutosave: NSViewRepresentable {
let name: String
func makeNSView(context: Context) -> NSView {
let view = NSView()
DispatchQueue.main.async { [weak view] in
var candidate = view?.superview
while let current = candidate, !(current is NSSplitView) {
candidate = current.superview
}
if let split = candidate as? NSSplitView {
split.autosaveName = name
split.identifier = NSUserInterfaceItemIdentifier(name)
}
}
return view
}
func updateNSView(_ nsView: NSView, context: Context) {}
}