Files
lichtkasten/Sources/Lichtkasten/Views/IPTCForm.swift
T

233 lines
8.9 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import SwiftUI
import LichtkastenCore
/// Editor texts for all fields (lists are kept as raw "a, b, c" text while typing).
typealias FieldTexts = [String: String]
extension IPTCValues {
func texts() -> FieldTexts {
var t: FieldTexts = [:]
for f in IPTCField.all { t[f.id] = self[f] }
return t
}
init(texts: FieldTexts) {
self.init()
for f in IPTCField.all { self[f] = (texts[f.id] ?? "").trimmingCharacters(in: .whitespaces) }
}
}
/// Section header (same order as PM, Leuchttisch look: amber label + hairline).
struct PMSectionHeader: View {
let title: String
var body: some View {
HStack(spacing: 10) {
Text(title.uppercased())
.font(.system(size: 11, weight: .bold))
.tracking(1.3)
.foregroundStyle(LK.amber)
Rectangle().fill(LK.border).frame(height: 1)
}
.padding(.top, 6)
}
}
/// The metadata form in Photo Mechanic's layout: blue section bars, labels left, big caption box,
/// optional PM checkboxes ("apply this field"), two columns for template / mass edit, one for the info window.
struct PMMetadataForm: View {
@Binding var texts: FieldTexts
var columns = 2
var mixed: Set<String> = []
var dirty: Set<String> = []
/// PM checkboxes; nil = no checkboxes (info window).
var applied: Binding<Set<String>>? = nil
var codes: CodeReplacements? = nil
/// ▾ lists (PM drop-down values)
var fieldLists: [String: [String]] = [:]
var onEdit: (String) -> Void = { _ in }
/// Extra rows (e.g. "Image Preferences → Label") inserted after Image Content.
var extraAfterContent: AnyView? = nil
var body: some View {
if columns == 2 {
HStack(alignment: .top, spacing: 18) {
column(0)
column(1)
}
} else {
VStack(alignment: .leading, spacing: 14) {
ForEach(IPTCSection.allCases, id: \.self) { sectionView($0) }
}
}
}
private func column(_ c: Int) -> some View {
VStack(alignment: .leading, spacing: 14) {
ForEach(IPTCSection.allCases.filter { $0.column == c }, id: \.self) { sectionView($0) }
}
.frame(maxWidth: .infinity, alignment: .top)
}
@ViewBuilder
private func sectionView(_ section: IPTCSection) -> some View {
VStack(alignment: .leading, spacing: 6) {
PMSectionHeader(title: section.rawValue)
ForEach(IPTCField.all.filter { $0.section == section }) { field in
PMFieldRow(field: field, text: binding(field), codes: codes, listValues: fieldLists[field.id] ?? [],
isMixed: mixed.contains(field.id) && !dirty.contains(field.id),
isDirty: dirty.contains(field.id),
applied: appliedBinding(field))
}
if section == .imageContent, let extra = extraAfterContent { extra }
}
}
private func appliedBinding(_ f: IPTCField) -> Binding<Bool>? {
guard let applied else { return nil }
return Binding(get: { applied.wrappedValue.contains(f.id) },
set: { on in if on { applied.wrappedValue.insert(f.id) } else { applied.wrappedValue.remove(f.id) } })
}
private func binding(_ f: IPTCField) -> Binding<String> {
Binding(get: { texts[f.id] ?? "" },
set: { value in
// Code replacement happens inside the text views (cursor stays in place).
texts[f.id] = value
// Editing a field ticks its checkbox (PM behaviour).
applied?.wrappedValue.insert(f.id)
onEdit(f.id)
})
}
}
struct PMFieldRow: View {
let field: IPTCField
@Binding var text: String
var codes: CodeReplacements?
var listValues: [String] = []
let isMixed: Bool
let isDirty: Bool
let applied: Binding<Bool>?
private var height: CGFloat? {
switch field.id {
case "caption": return 210
case "keywords": return 130
case "headline", "altText", "extDescription", "personInImage", "instructions", "usageTerms": return 62
default: return nil
}
}
var body: some View {
HStack(alignment: .top, spacing: 6) {
if let applied {
Toggle("", isOn: applied).toggleStyle(.checkbox).labelsHidden().padding(.top, 3)
}
VStack(alignment: .leading, spacing: 2) {
Text(field.pmLabel + ":")
.font(.system(size: 12))
.foregroundStyle(isDirty ? LK.amber : .primary)
.help(field.label)
// IIM limit: for keywords etc. it applies to each entry, not to the whole field.
if let max = field.iimMaxBytes, !text.contains("{") {
if field.kind == .list {
let long = IPTCValues.splitList(text).filter { $0.utf8.count > max }
if !long.isEmpty {
Text("\(long.count)× > \(max)").font(.caption2.monospacedDigit()).foregroundStyle(.red)
.help("Diese Einträge sind länger als \(max) Bytes (IIM-Limit pro Eintrag): " + long.joined(separator: ", "))
}
} else if text.utf8.count > max {
Text("\(text.utf8.count)/\(max)").font(.caption2.monospacedDigit()).foregroundStyle(.red)
.help("IPTC-IIM-Limit in Bytes – Agenturen kürzen längere Werte.")
}
}
}
.frame(width: 150, alignment: .leading)
.padding(.top, 3)
Group {
if field.id == "dateCreated" {
DateFieldEditor(text: $text)
} else if let h = height {
CodeTextView(text: $text, codes: codes)
.overlay(alignment: .topLeading) {
if isMixed && text.isEmpty {
Text("‹mehrere Werte›").foregroundStyle(.tertiary).padding(8).allowsHitTesting(false)
}
}
.frame(height: h)
} else {
CodeTextField(text: $text, codes: codes, placeholder: isMixed ? "‹mehrere Werte›" : "")
.frame(height: 22)
}
}
.frame(maxWidth: .infinity)
Menu {
if !listValues.isEmpty {
Section("Werte") {
ForEach(listValues.prefix(40), id: \.self) { v in
Button(v) {
if field.kind == .list {
let items = IPTCValues.splitList(text)
if !items.contains(v) { text = (items + [v]).joined(separator: ", ") }
} else {
text = v
}
}
}
}
}
Section("Variablen") {
ForEach(VariableExpander.documented, id: \.0) { v in
Button("\(v.0) – \(v.1)") { text += v.0 }
}
}
Button("Feld leeren") { text = "" }
} label: { Image(systemName: "chevron.down") }
.menuStyle(.borderlessButton)
.menuIndicator(.hidden)
.frame(width: 22)
.padding(.top, 2)
}
}
}
/// PM's Date row: popup "Capture Time" / "Today" / own date.
struct DateFieldEditor: View {
@Binding var text: String
enum Mode: String, CaseIterable { case capture = "Capture Time", today = "Heute", custom = "Datum eingeben", none = "Kein Datum" }
private var mode: Mode {
switch text {
case "{capturetime}": return .capture
case "{today}": return .today
case "": return .none
default: return .custom
}
}
var body: some View {
HStack {
Picker("", selection: Binding(get: { mode }, set: { m in
switch m {
case .capture: text = "{capturetime}"
case .today: text = "{today}"
case .none: text = ""
case .custom: if mode != .custom { text = ISO8601DateFormatter.string(from: Date(), timeZone: .current, formatOptions: [.withFullDate]) }
}
})) {
ForEach(Mode.allCases, id: \.self) { Text($0.rawValue).tag($0) }
}
.labelsHidden()
.frame(width: 170)
if mode == .custom {
TextField("JJJJ-MM-TT [HH:MM:SS]", text: $text).textFieldStyle(.roundedBorder)
} else {
Spacer()
}
}
}
}