aboutsummaryrefslogtreecommitdiff
path: root/Map/Presentation/Preferences/TemplatesPreferencesView.swift
blob: 42db1a3d2437064fcdb9fa29a99a8fd12864a574 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
// Copyright (C) 2024 Rubén Beltrán del Río

// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this program. If not, see https://map.tranquil.systems.

import SwiftUI

struct Template: Identifiable, Codable, Hashable {
  var id = UUID()
  var name: String
  var content: String

  init(name: String, content: String) {
    self.name = name
    self.content = content
  }

  func hash(into hasher: inout Hasher) {
    hasher.combine(id)
  }

  static func == (lhs: Template, rhs: Template) -> Bool {
    lhs.id == rhs.id
  }
}

struct SimpleTextEditor: NSViewRepresentable {
  @Binding var text: String

  func makeNSView(context: Context) -> NSScrollView {
    let scrollView = NSTextView.scrollableTextView()
    let textView = scrollView.documentView as! NSTextView

    textView.backgroundColor = .textBackgroundColor
    textView.allowsUndo = true
    textView.delegate = context.coordinator
    textView.string = text
    textView.isEditable = true
    textView.font = .monospacedSystemFont(ofSize: 14.0, weight: .regular)

    return scrollView
  }

  func updateNSView(_ nsView: NSScrollView, context: Context) {
    let textView = nsView.documentView as! NSTextView
    if textView.string != text {
      textView.string = text
    }
  }

  func makeCoordinator() -> Coordinator {
    Coordinator(self)
  }

  class Coordinator: NSObject, NSTextViewDelegate {
    var parent: SimpleTextEditor

    init(_ parent: SimpleTextEditor) {
      self.parent = parent
    }

    func textDidChange(_ notification: Notification) {
      if let textView = notification.object as? NSTextView {
        parent.text = textView.string
      }
    }
  }
}

struct TemplatesPreferencesView: View {
  @AppStorage("mapTemplates") private var templatesData: Data = Data()
  @State private var templates: [Template] = []
  @State private var selectedTemplate: Template?
  @State private var templateText: String = ""
  @State private var showingAddSheet = false
  @State private var newTemplateName = ""

  var body: some View {
    VStack(alignment: .leading, spacing: Dimensions.Spacing.regular) {
      Text("preferences.templates.title")
        .font(.Theme.Title.emphasized)
        .lineSpacing(Dimensions.LineHeight.title - Dimensions.FontSize.title)
      Text("preferences.templates.explanation")
        .font(.Theme.Body.regular)
        .kerning(Dimensions.Kerning.body)
        .lineSpacing(Dimensions.LineHeight.body - Dimensions.FontSize.body)
        .padding(.top, Dimensions.Spacing.loose)
        .padding(.bottom, Dimensions.Spacing.regular)
      HStack(spacing: 0) {
        VStack(alignment: .leading, spacing: 8) {
          HStack {
            Text("Templates")
              .font(.headline)
            
            Spacer()
            
            Button(action: { showingAddSheet = true }) {
              Image(systemName: "plus")
            }
            .buttonStyle(.borderless)
            
            Button(action: removeTemplate) {
              Image(systemName: "minus")
            }
            .buttonStyle(.borderless)
            .disabled(selectedTemplate == nil)
          }
          
          List(templates, selection: $selectedTemplate) { template in
            Text(template.name)
              .tag(template)
          }
          .listStyle(.sidebar)
        }
        .frame(width: 200)
        
        Divider()
        
        VStack(alignment: .leading, spacing: 8) {
          if let selected = selectedTemplate {
            HStack {
              Text("Template: \(selected.name)")
                .font(.headline)
              Spacer()
            }
            
            SimpleTextEditor(text: $templateText)
              .onChange(of: templateText) { _, newValue in
                updateSelectedTemplate(newValue)
              }
          } else {
            VStack {
              Spacer()
              Text("Select a template to edit")
                .foregroundColor(.secondary)
              Spacer()
            }
            .frame(maxWidth: .infinity, maxHeight: .infinity)
          }
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .padding(.leading)
      }
      .padding()
      .onAppear {
        loadTemplates()
      }
      .onChange(of: selectedTemplate) { _, newSelection in
        if let template = newSelection {
          templateText = template.content
        }
      }
      .sheet(isPresented: $showingAddSheet) {
        VStack(spacing: 16) {
          Text("Add New Template")
            .font(.headline)
          
          TextField("Template Name", text: $newTemplateName)
            .textFieldStyle(.roundedBorder)
          
          HStack {
            Button("Cancel") {
              showingAddSheet = false
              newTemplateName = ""
            }
            
            Spacer()
            
            Button("Add") {
              addTemplate()
            }
            .disabled(newTemplateName.isEmpty)
          }
        }
        .frame(width: 300, height: 120)
      }
    }.padding(.vertical, Dimensions.Spacing.loose)
      .padding(.horizontal, Dimensions.Spacing.indulgent)
  }

  private func loadTemplates() {
    if let decoded = try? JSONDecoder().decode([Template].self, from: templatesData) {
      templates = decoded
    } else {
      templates = [
        Template(
          name: "Basic Map",
          content:
            "Component A (90, 20)\nComponent B (70, 40)\nComponent A -> Component B\n\n[Note] (50, 10) This is a sample template"
        )
      ]
      saveTemplates()
    }
  }

  private func saveTemplates() {
    if let encoded = try? JSONEncoder().encode(templates) {
      templatesData = encoded
    }
  }

  private func addTemplate() {
    let newTemplate = Template(name: newTemplateName, content: "")
    templates.append(newTemplate)
    selectedTemplate = newTemplate
    templateText = ""
    saveTemplates()
    showingAddSheet = false
    newTemplateName = ""
  }

  private func removeTemplate() {
    guard let selected = selectedTemplate else { return }
    templates.removeAll { $0.id == selected.id }
    selectedTemplate = nil
    templateText = ""
    saveTemplates()
  }

  private func updateSelectedTemplate(_ newContent: String) {
    guard let selected = selectedTemplate,
      let index = templates.firstIndex(where: { $0.id == selected.id })
    else { return }

    templates[index].content = newContent
    saveTemplates()
  }
}

#Preview {
  TemplatesPreferencesView()
}