-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathContentView.swift
More file actions
576 lines (492 loc) · 20.2 KB
/
Copy pathContentView.swift
File metadata and controls
576 lines (492 loc) · 20.2 KB
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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
import SwiftUI
import WebKit
import AppKit
import UniformTypeIdentifiers
// MARK: - Ace controller
final class AceController: ObservableObject {
weak var webView: WKWebView?
func showFind() {
guard let webView = webView else { return }
webView.evaluateJavaScript("window.showFind ? window.showFind() : false") { _, error in
if let error = error {
print("Ace showFind error: \(error)")
}
}
}
/// Set the HTML content in the Ace editor (optionally beautified).
func setHTML(_ html: String, beautify: Bool = true) {
guard let webView = webView else { return }
// Escape characters that would break a single-quoted JS string
let escaped = html
.replacingOccurrences(of: "\\", with: "\\\\")
.replacingOccurrences(of: "\r", with: "")
.replacingOccurrences(of: "\n", with: "\\n")
.replacingOccurrences(of: "'", with: "\\'")
// Use the global `editor` defined in html-viewer-local.html
let js = "if (window.editor) { window.editor.setValue('\(escaped)', -1); }"
webView.evaluateJavaScript(js) { _, error in
if let error = error {
print("Ace setHTML error: \(error)")
}
}
}
/// Get the current HTML content from the Ace editor.
func getHTML(completion: @escaping (String) -> Void) {
guard let webView = webView else {
completion("")
return
}
webView.evaluateJavaScript("window.editor ? window.editor.getValue() : ''") { result, error in
if let error = error {
print("Ace getHTML error: \(error)")
completion("")
return
}
if let text = result as? String {
completion(text)
} else {
completion("")
}
}
}
}
// MARK: - Ace editor view
struct AceEditorWebView: NSViewRepresentable {
@ObservedObject var controller: AceController
func makeNSView(context: Context) -> WKWebView {
let config = WKWebViewConfiguration()
let webView = WKWebView(frame: .zero, configuration: config)
webView.setValue(false, forKey: "drawsBackground")
controller.webView = webView
if let url = Bundle.main.url(forResource: "html-viewer-local", withExtension: "html") {
webView.loadFileURL(url, allowingReadAccessTo: url.deletingLastPathComponent())
} else {
let html = """
<!doctype html>
<html><body><p style="font-family: -apple-system;">html-viewer-local.html not found in bundle.</p></body></html>
"""
webView.loadHTMLString(html, baseURL: nil)
}
return webView
}
func updateNSView(_ nsView: WKWebView, context: Context) {
// Content is driven by JS calls via the controller; nothing to update here.
}
}
// MARK: - Preview WebView
struct HTMLPreviewWebView: NSViewRepresentable {
let html: String
func makeNSView(context: Context) -> WKWebView {
let config = WKWebViewConfiguration()
let webView = WKWebView(frame: .zero, configuration: config)
webView.setValue(false, forKey: "drawsBackground")
webView.loadHTMLString(html, baseURL: nil)
return webView
}
func updateNSView(_ nsView: WKWebView, context: Context) {
nsView.loadHTMLString(html, baseURL: nil)
}
}
// MARK: - Main Content View
struct ContentView: View {
// Gotenberg endpoint (Synology)
private let gotenbergURL = URL(string: "http://localhost:3000/forms/chromium/convert/html")!
@StateObject private var aceController = AceController()
@AppStorage(EditorStorage.lastHTMLKey) private var persistedHTML: String = SampleHTML.default
@State private var currentHTML: String = SampleHTML.default
@State private var isConverting = false
@State private var statusMessage: String = "Edit HTML on the left, update preview on the right, then export to PDF."
@State private var lastPDFURL: URL?
@State private var livePreviewTimer: Timer?
init() {
let savedHTML = UserDefaults.standard.string(forKey: EditorStorage.lastHTMLKey) ?? SampleHTML.default
_persistedHTML = AppStorage(wrappedValue: savedHTML, EditorStorage.lastHTMLKey)
_currentHTML = State(initialValue: savedHTML)
}
var body: some View {
ZStack {
// Background
LinearGradient(
colors: [
Color(nsColor: .windowBackgroundColor),
Color(.sRGB, red: 0.10, green: 0.12, blue: 0.16, opacity: 1.0)
],
startPoint: .topLeading,
endPoint: .bottomTrailing
)
.ignoresSafeArea()
VStack(spacing: 12) {
header
toolbar
// Big split workspace
HSplitView {
// Left: Ace editor
VStack(alignment: .leading, spacing: 4) {
headerLabel(
title: "HTML Editor",
subtitle: "Ace + Monokai + js-beautify"
)
RoundedRectangle(cornerRadius: 10, style: .continuous)
.fill(Color.black.opacity(0.9))
.overlay(
RoundedRectangle(cornerRadius: 10)
.stroke(Color.white.opacity(0.12), lineWidth: 1)
)
.overlay(
AceEditorWebView(controller: aceController)
.frame(maxWidth: .infinity, maxHeight: .infinity)
.cornerRadius(10)
)
.frame(maxWidth: .infinity, maxHeight: .infinity)
.shadow(color: .black.opacity(0.5), radius: 18, x: 0, y: 12)
}
.padding(4)
// Right: Preview
VStack(alignment: .leading, spacing: 4) {
headerLabel(
title: "Preview",
subtitle: "Rendered HTML (WebKit)"
)
RoundedRectangle(cornerRadius: 10, style: .continuous)
.fill(Color(nsColor: .windowBackgroundColor))
.overlay(
RoundedRectangle(cornerRadius: 10)
.stroke(Color.white.opacity(0.12), lineWidth: 1)
)
.overlay(
HTMLPreviewWebView(html: currentHTML)
.frame(maxWidth: .infinity, maxHeight: .infinity)
.cornerRadius(10)
)
.frame(maxWidth: .infinity, maxHeight: .infinity)
.shadow(color: .black.opacity(0.35), radius: 16, x: 0, y: 12)
}
.padding(4)
}
.padding(.vertical, 4)
// Status bar
HStack(spacing: 8) {
Image(systemName: "info.circle")
.font(.system(size: 12))
.foregroundStyle(.secondary)
Text(statusMessage)
.font(.system(size: 11))
.foregroundStyle(.secondary)
.lineLimit(2)
.truncationMode(.tail)
Spacer()
}
.padding(.horizontal, 8)
.padding(.bottom, 4)
}
.padding(12)
}
.frame(minWidth: 1200, minHeight: 750)
.onAppear {
currentHTML = persistedHTML
// Load saved HTML into Ace editor once WebView is ready.
DispatchQueue.main.asyncAfter(deadline: .now() + 0.8) {
aceController.setHTML(currentHTML, beautify: true)
}
// Start a lightweight polling timer to keep the preview in sync with Ace.
livePreviewTimer?.invalidate()
livePreviewTimer = Timer.scheduledTimer(withTimeInterval: 0.7, repeats: true) { _ in
aceController.getHTML { html in
DispatchQueue.main.async {
let trimmed = html.trimmingCharacters(in: .whitespacesAndNewlines)
persistEditorHTML(html)
if !trimmed.isEmpty {
currentHTML = html
}
}
}
}
}
.onDisappear {
livePreviewTimer?.invalidate()
livePreviewTimer = nil
}
.onReceive(NotificationCenter.default.publisher(for: .showEditorFind)) { _ in
aceController.showFind()
}
}
// MARK: - Header & Toolbar
private var header: some View {
HStack(alignment: .firstTextBaseline, spacing: 8) {
VStack(alignment: .leading, spacing: 4) {
Text("Gotenberg HTML → PDF")
.font(.system(size: 20, weight: .semibold, design: .rounded))
.foregroundStyle(.primary)
Text("Ace-powered HTML editor on the left, live preview on the right, and one-click export to PDF via Synology Gotenberg.")
.font(.system(size: 12, weight: .regular))
.foregroundStyle(.secondary)
}
Spacer()
}
.padding(.horizontal, 8)
}
private var toolbar: some View {
HStack(spacing: 8) {
Button {
currentHTML = SampleHTML.default
aceController.setHTML(currentHTML, beautify: true)
persistEditorHTML(currentHTML)
statusMessage = "Loaded sample HTML"
} label: {
Label("Sample", systemImage: "doc.text.magnifyingglass")
}
Button(role: .destructive) {
currentHTML = ""
aceController.setHTML("", beautify: false)
persistEditorHTML(currentHTML)
statusMessage = "Editor cleared"
} label: {
Label("Clear", systemImage: "trash")
}
Divider().frame(height: 22)
Button {
openHTMLFile()
} label: {
Label("Open HTML…", systemImage: "folder")
}
Button {
syncFromEditor { html in
saveHTMLFile(html: html)
}
} label: {
Label("Save HTML…", systemImage: "square.and.arrow.down")
}
Divider().frame(height: 22)
Button {
syncFromEditor { html in
currentHTML = html
statusMessage = "Preview updated"
}
} label: {
Label("Update Preview", systemImage: "arrow.triangle.2.circlepath")
}
Divider().frame(height: 22)
Button {
syncFromEditor { html in
Task {
await convertToPDF(html: html)
}
}
} label: {
Label("Export PDF", systemImage: "doc.richtext")
}
.buttonStyle(.borderedProminent)
.tint(.accentColor)
.disabled(isConverting)
if isConverting {
ProgressView()
.controlSize(.small)
.padding(.leading, 4)
}
Spacer()
if let lastPDFURL {
Button {
NSWorkspace.shared.open(lastPDFURL)
} label: {
Label("Open Last PDF", systemImage: "arrow.up.right.square")
}
}
}
.buttonStyle(.bordered)
.controlSize(.small)
.padding(.horizontal, 8)
}
@ViewBuilder
private func headerLabel(title: String, subtitle: String) -> some View {
VStack(alignment: .leading, spacing: 2) {
Text(title)
.font(.system(size: 13, weight: .semibold, design: .rounded))
Text(subtitle)
.font(.system(size: 11))
.foregroundStyle(.secondary)
}
.padding(.leading, 2)
}
private func persistEditorHTML(_ html: String) {
persistedHTML = html
}
// MARK: - File operations
private func openHTMLFile() {
let panel = NSOpenPanel()
panel.allowedContentTypes = [
UTType(filenameExtension: "html")!,
UTType(filenameExtension: "htm")!
]
panel.allowsMultipleSelection = false
panel.canChooseDirectories = false
if panel.runModal() == .OK, let url = panel.url {
do {
let data = try Data(contentsOf: url)
if let text = String(data: data, encoding: .utf8) {
currentHTML = text
aceController.setHTML(text, beautify: true)
persistEditorHTML(text)
statusMessage = "Loaded \(url.lastPathComponent)"
} else {
statusMessage = "❌ Could not decode \(url.lastPathComponent) as UTF-8."
}
} catch {
statusMessage = "❌ Error reading file: \(error.localizedDescription)"
}
}
}
private func saveHTMLFile(html: String) {
let panel = NSSavePanel()
panel.allowedContentTypes = [UTType(filenameExtension: "html")!]
panel.nameFieldStringValue = "document.html"
panel.canCreateDirectories = true
if panel.runModal() == .OK, let url = panel.url {
do {
try html.data(using: .utf8)?.write(to: url, options: .atomic)
statusMessage = "Saved HTML to \(url.path)"
} catch {
statusMessage = "❌ Error saving HTML: \(error.localizedDescription)"
}
} else {
statusMessage = "Save cancelled."
}
}
/// Pull latest HTML from Ace editor before actions like preview / export / save.
private func syncFromEditor(_ completion: @escaping (String) -> Void) {
aceController.getHTML { html in
DispatchQueue.main.async {
let trimmed = html.trimmingCharacters(in: .whitespacesAndNewlines)
self.currentHTML = trimmed.isEmpty ? self.currentHTML : html
let latestHTML = html.isEmpty ? self.currentHTML : html
self.persistEditorHTML(latestHTML)
completion(latestHTML)
}
}
}
// MARK: - Gotenberg integration
@MainActor
private func convertToPDF(html: String) async {
let trimmed = html.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty else {
statusMessage = "Nothing to export – HTML is empty."
return
}
isConverting = true
statusMessage = "Sending HTML to Gotenberg…"
defer { isConverting = false }
guard let htmlData = trimmed.data(using: .utf8) else {
statusMessage = "Failed to encode HTML as UTF-8."
return
}
let boundary = "Boundary-\(UUID().uuidString)"
var request = URLRequest(url: gotenbergURL)
request.httpMethod = "POST"
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
var body = Data()
func appendString(_ string: String) {
if let data = string.data(using: .utf8) {
body.append(data)
}
}
appendString("--\(boundary)\r\n")
appendString("Content-Disposition: form-data; name=\"files\"; filename=\"index.html\"\r\n")
appendString("Content-Type: text/html; charset=utf-8\r\n\r\n")
body.append(htmlData)
appendString("\r\n")
appendString("--\(boundary)--\r\n")
request.httpBody = body
do {
let (data, response) = try await URLSession.shared.data(for: request)
guard let http = response as? HTTPURLResponse else {
statusMessage = "Failed: no HTTP response."
return
}
guard (200..<300).contains(http.statusCode) else {
let snippet = String(data: data, encoding: .utf8) ?? "<no body>"
statusMessage = "Gotenberg error \(http.statusCode): \(snippet.prefix(120))"
return
}
let baseName = inferFriendlyBaseName(from: html)
let pdfFilename = baseName + ".pdf"
let downloads = FileManager.default.urls(for: .downloadsDirectory, in: .userDomainMask).first
?? FileManager.default.temporaryDirectory
let pdfURL = downloads.appendingPathComponent(pdfFilename)
try data.write(to: pdfURL, options: .atomic)
lastPDFURL = pdfURL
statusMessage = "PDF created in Downloads: \(pdfFilename)"
} catch {
statusMessage = "Request failed: \(error.localizedDescription)"
}
}
private func inferFriendlyBaseName(from html: String) -> String {
// Try to use the <title> if present
if let titleRange = html.range(of: "<title>", options: .caseInsensitive),
let endRange = html.range(of: "</title>", options: .caseInsensitive, range: titleRange.upperBound..<html.endIndex) {
let title = html[titleRange.upperBound..<endRange.lowerBound]
.trimmingCharacters(in: .whitespacesAndNewlines)
if !title.isEmpty {
return sanitizeFilename(String(title))
}
}
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd_HHmm"
return "Gotenberg-\(formatter.string(from: Date()))"
}
private func sanitizeFilename(_ text: String) -> String {
let replaced = text
.replacingOccurrences(of: "/", with: "-")
.replacingOccurrences(of: ":", with: "-")
let trimmed = replaced.trimmingCharacters(in: .whitespacesAndNewlines)
return trimmed.isEmpty ? "Document" : trimmed
}
}
// MARK: - Persistence
enum EditorStorage {
static let lastHTMLKey = "lastHTMLInEditor"
}
extension Notification.Name {
static let showEditorFind = Notification.Name("showEditorFind")
}
// MARK: - Sample HTML
enum SampleHTML {
static let `default`: String = """
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Sample Gotenberg PDF</title>
<style>
body {
font-family: -apple-system, system-ui, BlinkMacSystemFont, "Segoe UI", sans-serif;
margin: 0;
padding: 2rem;
background: #f4f5fb;
}
h1 {
margin-top: 0;
color: #222;
}
.card {
background: #ffffff;
padding: 1.5rem 2rem;
border-radius: 16px;
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.10);
max-width: 720px;
}
.muted {
color: #666;
font-size: 0.9rem;
}
</style>
</head>
<body>
<h1>Hello from macOS → Synology Gotenberg 👋</h1>
<div class="card">
<p>This is a sample HTML document.</p>
<p>Edit this content in the Ace editor, click <strong>Update Preview</strong>, then <strong>Export PDF</strong>.</p>
<p class="muted">Your Synology Gotenberg container will render the final PDF.</p>
</div>
</body>
</html>
"""
}