-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHTMLPopup.swift
More file actions
1149 lines (999 loc) · 44.1 KB
/
HTMLPopup.swift
File metadata and controls
1149 lines (999 loc) · 44.1 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
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import Cocoa
import WebKit
import CommonCrypto
import UniformTypeIdentifiers
func logError(_ message: String) {
fputs("ERROR: \(message)\n", stderr)
}
func logFatalError(_ message: String) -> Never {
NSApplication.shared.terminate(nil)
fatalError("FATAL: \(message)")
}
func readStdin() -> String {
var input = ""
while let line = readLine() {
input += line + "\n"
}
return input
}
struct Options {
var html: String = ""
var url: URL? = nil
var title: String = ""
var width: CGFloat = 800
var height: CGFloat = 600
var env: [String: Any] = [:] // Default empty dictionary
var staticDirectory: String? = nil
var filePath: String? = nil
var storageID: String? = nil
}
var currentVersion = "dev" // Default version, will be overridden by build system
func printUsage() {
fputs("""
Usage: htmlpopup [OPTIONS] content
Arguments:
content
HTML content string, path to an HTML file, a URL, or a directory.
Use '-' to read HTML from stdin.
If a directory is provided, it will serve 'index.html' from that directory
or generate a directory listing if 'index.html' is not found.
Options:
--title <title> Set the window title (default: <empty>).
--width <width> Set the window width (default: 800)
--height <height> Set the window height (default: 600)
--env <json_object> Provide a JSON object to be injected as window.env in the web view.
--env.<key> <value> Provide individual key-value pairs to be injected as window.env.
Values are parsed as JSON if possible, otherwise as strings.
--version Print the version of htmlpopup.
--help Print this help message.
Javascript API:
Your HTML has access to the following Javascript APIs:
interface App {
// Properties
theme: 'light' | 'dark'; // Current system theme
// Window Control
finish(message: string): void; // Close window and print message to stdout
setSize(width: number, height: number): void; // Resize the window
setFullscreen(enabled: boolean): void; // Toggle fullscreen mode
setFloating(enabled: boolean): void; // Pin/unpin window to stay on top
setTitle(title: string): void; // Change the window title
// File System
selectFolder(): Promise<string>; // Open native folder picker dialog
selectFile(options?: { // Open native file picker dialog
canChooseFiles?: boolean;
canChooseDirectories?: boolean;
allowsMultipleSelection?: boolean;
allowedFileTypes?: string[];
}): Promise<string | string[]>;
saveFile(content: string, fileName?: string): Promise<string>; // Open save dialog
readFile(filePath: string): Promise<string>; // Read file content as text
readFileAsDataURL(filePath: string): Promise<string>; // Read file as base64 Data URL
revealInFinder(path: string): void; // Show file/folder in Finder
// Terminal Output
writeLine(text: string): void; // Print line to stdout
}
declare const window: {
env: Record<string, any>; // From --env or --env.<key>
app: App;
};
// Events
'files-dropped': CustomEvent<{ files: string[] }>; // Fired when files are dropped
'themechange': CustomEvent<{ theme: 'light' | 'dark' }>; // Fired on theme change
// CSS Variables (auto-adapt to theme)
--htmlpopup-background, --htmlpopup-text, --htmlpopup-border,
--htmlpopup-surface, --htmlpopup-link, --htmlpopup-muted
Examples:
htmlpopup "<h1>Hello, World!</h1>"
htmlpopup my_page.html
htmlpopup --width 1024 --height 768 --title "My App" ./static/
htmlpopup --env.API_KEY "secret" --env.DEBUG true app.html
echo "<p>From stdin</p>" | htmlpopup -
""", stderr)
}
struct ArgumentError: Error {
let message: String
}
func parseArguments() throws -> Options {
var options = Options()
let args = Array(CommandLine.arguments.dropFirst())
var envArgs: [String: Any] = [:]
var parsingFlags = true
// 1. Fast path for global flags
if args.contains("--version") {
print("htmlpopup version: \(currentVersion)")
exit(0)
}
if args.contains("--help") {
printUsage()
exit(0)
}
var argIterator = args.makeIterator()
while let arg = argIterator.next() {
// 2. Handle the "end of flags" marker --
if arg == "--" {
parsingFlags = false
continue
}
if parsingFlags && arg.hasPrefix("--") {
if arg.hasPrefix("--env.") {
let key = String(arg.dropFirst(6))
guard let valueString = argIterator.next() else {
throw ArgumentError(message: "Missing value for \(arg)")
}
// Attempt to parse value as JSON (e.g., numbers, booleans), fallback to string
if let data = valueString.data(using: .utf8),
let jsonValue = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) {
envArgs[key] = jsonValue
} else {
envArgs[key] = valueString
}
} else {
guard let value = argIterator.next() else {
throw ArgumentError(message: "Missing value for \(arg)")
}
switch arg {
case "--id": options.storageID = value
case "--title": options.title = value
case "--width": options.width = CGFloat(Double(value) ?? 800)
case "--height": options.height = CGFloat(Double(value) ?? 600)
case "--env":
if let data = value.data(using: .utf8),
let dict = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] {
options.env = dict
} else {
throw ArgumentError(message: "Invalid JSON for --env")
}
default:
throw ArgumentError(message: "Unknown option: \(arg)")
}
}
} else {
// 3. Handle Content Argument
if options.html.isEmpty && options.url == nil && options.staticDirectory == nil {
if arg == "-" {
options.html = readStdin()
} else if let url = URL(string: arg), let scheme = url.scheme?.lowercased(), ["http", "https"].contains(scheme) {
options.url = url
} else {
// Check if it is a directory or file
var isDir: ObjCBool = false
if FileManager.default.fileExists(atPath: arg, isDirectory: &isDir) {
if isDir.boolValue {
options.staticDirectory = arg // Allowed even without index.html now
} else {
options.filePath = arg
options.html = try String(contentsOfFile: arg, encoding: .utf8)
}
} else {
// If it ends in .html but doesn't exist, warn the user
if arg.hasSuffix(".html") || arg.hasSuffix(".htm") {
logError("Warning: '\(arg)' looks like a file but was not found. Treating as raw string.")
}
options.html = arg
}
}
} else {
throw ArgumentError(message: "Unexpected argument: \(arg)")
}
}
}
options.env = options.env.merging(envArgs) { (_, new) in new }
guard !(options.html.isEmpty && options.url == nil && options.staticDirectory == nil) else {
throw ArgumentError(message: "No content provided (HTML string, file, or URL).")
}
return options
}
func stableUUID(from string: String) -> UUID {
let data = Data(string.utf8)
var hash = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH))
data.withUnsafeBytes { _ = CC_SHA256($0.baseAddress, CC_LONG(data.count), &hash) }
// Use first 16 bytes for UUID
return UUID(uuid: (hash[0], hash[1], hash[2], hash[3], hash[4], hash[5], hash[6], hash[7],
hash[8], hash[9], hash[10], hash[11], hash[12], hash[13], hash[14], hash[15]))
}
class WindowController: NSWindowController, NSWindowDelegate {
private var pinButton: NSButton!
public var isPinned: Bool {
get {
return window?.level == .floating
}
set {
window?.level = newValue ? .floating : .normal
updatePinButtonImage()
}
}
init(width: CGFloat, height: CGFloat, title: String) {
let window = NSWindow(
contentRect: NSRect(x: 0, y: 0, width: width, height: height),
styleMask: [.titled, .closable, .miniaturizable, .resizable],
backing: .buffered,
defer: false
)
window.title = title
window.level = .floating // Window starts as floating
window.center()
// Added .fullScreenPrimary to support standard macOS fullscreen behavior
window.collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary, .fullScreenPrimary]
window.isReleasedWhenClosed = false
super.init(window: window)
window.delegate = self
setupPinButton()
setupKeyEventMonitor()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private var keyEventMonitor: Any?
private func setupPinButton() {
guard let window = self.window else { return }
pinButton = NSButton(frame: NSRect(x: 0, y: 0, width: 16, height: 16))
pinButton.bezelStyle = .texturedRounded
pinButton.isBordered = false
pinButton.imagePosition = .imageOnly
pinButton.state = isPinned ? .on : .off // Set initial state based on window level
updatePinButtonImage() // Set initial image
pinButton.toolTip = "Keep window floating on top"
pinButton.target = self
pinButton.action = #selector(togglePin)
// Position the button in the titlebar
if let titlebarView = window.standardWindowButton(.closeButton)?.superview {
titlebarView.addSubview(pinButton)
if let closeButton = window.standardWindowButton(.closeButton) {
let margin: CGFloat = 6
let pinButtonX = titlebarView.frame.width - pinButton.frame.width - margin
let pinButtonY = closeButton.frame.minY
pinButton.frame.origin = CGPoint(x: pinButtonX, y: pinButtonY)
pinButton.autoresizingMask = [.minXMargin]
}
}
}
private func updatePinButtonImage() {
let imageName = isPinned ? "pin.fill" : "pin"
pinButton.image = NSImage(systemSymbolName: imageName, accessibilityDescription: isPinned ? "Unpin Window" : "Pin Window")
}
@objc private func togglePin() {
isPinned.toggle()
}
// Set up a local key event monitor that will detect ESC key presses
private func setupKeyEventMonitor() {
keyEventMonitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { [weak self] event in
if event.keyCode == 53 { // ESC key
// Unfloat the window and move it to background
self?.isPinned = false
self?.window?.orderBack(nil)
return nil // Consume the event
}
return event // Pass other events through
}
}
deinit {
if let monitor = keyEventMonitor {
NSEvent.removeMonitor(monitor)
}
}
}
class DraggableWebView: WKWebView {
weak var appDelegate: AppDelegate?
override func awakeFromNib() {
super.awakeFromNib()
registerForDraggedTypes([.fileURL, .string])
}
override init(frame: CGRect, configuration: WKWebViewConfiguration) {
super.init(frame: frame, configuration: configuration)
registerForDraggedTypes([.fileURL, .string])
}
required init?(coder: NSCoder) {
super.init(coder: coder)
registerForDraggedTypes([.fileURL, .string])
}
override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation {
if sender.draggingPasteboard.types?.contains(.fileURL) == true {
return .copy
}
return []
}
override func performDragOperation(_ sender: NSDraggingInfo) -> Bool {
guard let urls = sender.draggingPasteboard.readObjects(forClasses: [NSURL.self]) as? [URL] else {
return false
}
let paths = urls.map { $0.path }
do {
let jsonData = try JSONSerialization.data(withJSONObject: paths, options: [])
guard let jsonString = String(data: jsonData, encoding: .utf8) else { return false }
let jsCallback = """
window.dispatchEvent(new CustomEvent('files-dropped', {
detail: { files: \(jsonString) }
}));
"""
evaluateJavaScript(jsCallback)
} catch {
logError("JSON serialization error: \(error)")
}
return true
}
}
class AppDelegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKScriptMessageHandler {
var windowController: WindowController?
var webView: WKWebView?
var closeString: String?
let options: Options
private var themeObserver: NSKeyValueObservation?
init(options: Options) {
self.options = options
super.init()
}
func applicationDidFinishLaunching(_ notification: Notification) {
NSApplication.shared.setActivationPolicy(.regular)
setupMenuBar()
setupWindowAndWebView()
handleThemeChange()
setupThemeObserver()
}
private func setupMenuBar() {
let menuBar = NSMenu()
NSApplication.shared.mainMenu = menuBar
let fileMenuItem = NSMenuItem()
menuBar.addItem(fileMenuItem)
let fileMenu = NSMenu(title: "File")
fileMenuItem.submenu = fileMenu
fileMenu.addItem(NSMenuItem(title: "Close Window",
action: #selector(NSWindow.performClose(_:)),
keyEquivalent: "w"))
fileMenu.addItem(NSMenuItem.separator())
fileMenu.addItem(NSMenuItem(title: "Quit",
action: #selector(NSApplication.terminate(_:)),
keyEquivalent: "q"))
let editMenuItem = NSMenuItem()
menuBar.addItem(editMenuItem)
let editMenu = NSMenu(title: "Edit")
editMenuItem.submenu = editMenu
editMenu.addItem(NSMenuItem(title: "Undo",
action: Selector(("undo:")),
keyEquivalent: "z"))
editMenu.addItem(NSMenuItem(title: "Redo",
action: Selector(("redo:")),
keyEquivalent: "Z"))
editMenu.addItem(NSMenuItem.separator())
editMenu.addItem(NSMenuItem(title: "Cut",
action: #selector(NSText.cut(_:)),
keyEquivalent: "x"))
editMenu.addItem(NSMenuItem(title: "Copy",
action: #selector(NSText.copy(_:)),
keyEquivalent: "c"))
editMenu.addItem(NSMenuItem(title: "Paste",
action: #selector(NSText.paste(_:)),
keyEquivalent: "v"))
editMenu.addItem(NSMenuItem(title: "Select All",
action: #selector(NSText.selectAll(_:)),
keyEquivalent: "a"))
}
private func setupThemeObserver() {
if #available(macOS 10.14, *) {
themeObserver = NSApp.observe(\.effectiveAppearance) { [weak self] _, _ in
DispatchQueue.main.async {
self?.handleThemeChange()
}
}
}
}
private func handleThemeChange() {
guard let window = windowController?.window,
let webView = self.webView else { return }
// Update window appearance
if #available(macOS 10.14, *) {
let isDarkMode = NSApp.effectiveAppearance.bestMatch(from: [.aqua, .darkAqua]) == .darkAqua
window.appearance = NSAppearance(named: isDarkMode ? .darkAqua : .aqua)
// Notify web content about theme change
let themeScript = """
if (window.app && window.app.onThemeChange) {
window.app.onThemeChange('\(isDarkMode ? "dark" : "light")');
}
// Also dispatch a custom event for more flexibility
window.dispatchEvent(new CustomEvent('themechange', {
detail: { theme: '\(isDarkMode ? "dark" : "light")' }
}));
"""
webView.evaluateJavaScript(themeScript) { _, error in
if let error = error {
print("Error executing theme change script: \(error)")
}
}
}
}
private func setupWindowAndWebView() {
windowController = WindowController(
width: options.width,
height: options.height,
title: options.title
)
let userContentController = WKUserContentController()
userContentController.add(self, name: "app")
setupUserScripts(userContentController: userContentController, env: options.env)
let config = WKWebViewConfiguration()
config.userContentController = userContentController
// 1. GENERATE UNIQUE ORIGIN
// We use http://[ID].local to guarantee localStorage partitioning by hostname.
// We use a stable hash of the source to keep the hostname clean and consistent.
let identifierSource: String
if let sid = options.storageID {
identifierSource = sid
} else if let fp = options.filePath {
identifierSource = fp // Stable path, content can change
} else if let sd = options.staticDirectory {
identifierSource = sd
} else if let url = options.url {
identifierSource = url.absoluteString
} else if !options.html.isEmpty {
identifierSource = "html-" + stableUUID(from: options.html).uuidString
} else {
identifierSource = "default"
}
let hostID = stableUUID(from: identifierSource).uuidString.lowercased().replacingOccurrences(of: "-", with: "")
let dummyOrigin = URL(string: "http://\(hostID).local")!
// 2. CONFIGURE PERSISTENCE
config.websiteDataStore = WKWebsiteDataStore.default()
config.preferences.setValue(true, forKey: "developerExtrasEnabled")
config.preferences.setValue(true, forKey: "allowFileAccessFromFileURLs")
config.setValue(true, forKey: "allowUniversalAccessFromFileURLs")
if #available(macOS 11.0, *) {
config.defaultWebpagePreferences.allowsContentJavaScript = true
} else {
config.preferences.javaScriptEnabled = true
}
guard let contentView = windowController?.window?.contentView else {
logFatalError("Window contentView is nil.")
}
webView = DraggableWebView(frame: contentView.bounds, configuration: config)
guard let webView = webView else {
logFatalError("Failed to create WKWebView.")
}
(webView as? DraggableWebView)?.appDelegate = self
webView.autoresizingMask = [.width, .height]
webView.navigationDelegate = self
if #available(macOS 10.14, *) {
webView.setValue(false, forKey: "drawsBackground")
}
// 3. LOAD CONTENT
if let staticDir = options.staticDirectory {
let dirURL = URL(fileURLWithPath: staticDir, isDirectory: true)
let indexURL = dirURL.appendingPathComponent("index.html")
if FileManager.default.fileExists(atPath: indexURL.path) {
if var html = try? String(contentsOf: indexURL) {
// Inject <base> tag to support relative paths while using a custom origin
let baseTag = "<base href=\"\(dirURL.absoluteString)\">"
if html.lowercased().contains("<head>") {
html = html.replacingOccurrences(of: "<head>", with: "<head>\(baseTag)", options: .caseInsensitive)
} else {
html = "<head>\(baseTag)</head>" + html
}
webView.loadHTMLString(html, baseURL: dummyOrigin)
} else {
// Fallback to file URL if reading fails
webView.loadFileURL(indexURL, allowingReadAccessTo: dirURL)
}
} else {
// Generate directory listing if index.html is missing
let html = generateDirectoryListing(for: dirURL)
webView.loadHTMLString(html, baseURL: dirURL)
}
} else if let url = options.url {
webView.load(URLRequest(url: url))
} else if !options.html.isEmpty {
let baseURL: URL
if let fp = options.filePath {
baseURL = URL(fileURLWithPath: fp).deletingLastPathComponent()
} else {
baseURL = URL(fileURLWithPath: FileManager.default.currentDirectoryPath, isDirectory: true)
}
let baseTag = "<base href=\"\(baseURL.absoluteString)\">"
var html = options.html
if html.lowercased().contains("<head>") {
html = html.replacingOccurrences(of: "<head>", with: "<head>\(baseTag)", options: .caseInsensitive)
} else {
html = "<head>\(baseTag)</head>" + html
}
webView.loadHTMLString(html, baseURL: dummyOrigin)
}
contentView.addSubview(webView)
windowController?.showWindow(nil)
NSApplication.shared.activate(ignoringOtherApps: true)
windowController?.window?.makeKeyAndOrderFront(nil)
}
func webView(_ webView: WKWebView,
decidePolicyFor navigationAction: WKNavigationAction,
decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
if let url = navigationAction.request.url {
let host = url.host?.lowercased() ?? ""
let scheme = url.scheme?.lowercased() ?? ""
// 1. Allow our internal partitioned origins
if host.hasSuffix(".local") {
decisionHandler(.allow)
return
}
// 2. Allow standard web/file schemes
if ["http", "https", "about", "file"].contains(scheme) {
decisionHandler(.allow)
return
}
// 3. Hand off external protocols (mailto, slack, etc) to the system
if !NSWorkspace.shared.open(url) {
logError("Failed to open URL: \(url)")
}
decisionHandler(.cancel)
return
}
decisionHandler(.allow)
}
func setupUserScripts(userContentController: WKUserContentController, env: [String: Any] = [:]) {
// Convert the dictionary to a JSON string
var envJsonString = "{}"
if let jsonData = try? JSONSerialization.data(withJSONObject: env, options: []),
let jsonString = String(data: jsonData, encoding: .utf8) {
envJsonString = jsonString
}
// Get current theme state
let isDarkMode = NSApp.effectiveAppearance.bestMatch(from: [.aqua, .darkAqua]) == .darkAqua
let currentTheme = isDarkMode ? "dark" : "light"
let defaultThemeCSS = """
:root {
color-scheme: light dark;
--htmlpopup-background: #ffffff;
--htmlpopup-text: #1c1c1e;
--htmlpopup-border: #d1d1d6;
--htmlpopup-surface: rgba(249, 249, 251, 0.9);
--htmlpopup-link: #0a84ff;
--htmlpopup-muted: #6e6e73;
}
:root[data-theme='dark'],
.dark {
color-scheme: dark;
--htmlpopup-background: #1c1c1e;
--htmlpopup-text: #f5f5f7;
--htmlpopup-border: #2c2c2e;
--htmlpopup-surface: rgba(44, 44, 46, 0.85);
--htmlpopup-link: #63a4ff;
--htmlpopup-muted: #8e8e93;
}
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
background-color: var(--htmlpopup-background);
color: var(--htmlpopup-text);
}
a, button {
color: inherit;
cursor: pointer;
}
input,
textarea,
select {
color: inherit;
}
code,
pre {
color: inherit;
}
"""
// First inject ENV
let envScript = WKUserScript(
source: "window.env = \(envJsonString);",
injectionTime: .atDocumentStart,
forMainFrameOnly: true
)
// Provide baseline theming tokens so content inherits light/dark styling automatically.
let cssInjectionScript = WKUserScript(
source: """
(function() {
if (document.getElementById('htmlpopup-theme-style')) { return; }
const css = `\(defaultThemeCSS)`;
const style = document.createElement('style');
style.id = 'htmlpopup-theme-style';
style.type = 'text/css';
style.textContent = css;
(document.head || document.documentElement).appendChild(style);
})();
""",
injectionTime: .atDocumentStart,
forMainFrameOnly: true
)
// Then inject app API
let appScript = WKUserScript(
source: """
window.app = {
theme: '\(currentTheme)',
onThemeChange: null,
finish: function(message) {
window.webkit.messageHandlers.app.postMessage({ action: "finish", message: message });
},
setSize: function(width, height) {
window.webkit.messageHandlers.app.postMessage({ action: "setSize", width: width, height: height });
},
setFullscreen: function(enabled) {
window.webkit.messageHandlers.app.postMessage({ action: "setFullscreen", enabled: !!enabled });
},
setFloating: function(enabled) {
window.webkit.messageHandlers.app.postMessage({ action: "setFloating", enabled: !!enabled });
},
setTitle: function(title) {
window.webkit.messageHandlers.app.postMessage({ action: "setTitle", title: title });
},
revealInFinder: function(path) {
window.webkit.messageHandlers.app.postMessage({ action: "revealInFinder", path: path });
},
selectFolder: function() {
return new Promise((resolve, reject) => {
const callbackId = 'callback_' + Math.random().toString(36).substr(2, 9);
window[callbackId] = { resolve: resolve, reject: reject };
window.webkit.messageHandlers.app.postMessage({
action: "selectFolder",
callbackId: callbackId
});
});
},
selectFile: function(options = {}) {
return new Promise((resolve, reject) => {
const callbackId = 'callback_' + Math.random().toString(36).substr(2, 9);
window[callbackId] = { resolve: resolve, reject: reject };
window.webkit.messageHandlers.app.postMessage({
action: "selectFile",
callbackId: callbackId,
options: options
});
});
},
saveFile: function(content, fileName) {
return new Promise((resolve, reject) => {
const callbackId = 'callback_' + Math.random().toString(36).substr(2, 9);
window[callbackId] = { resolve: resolve, reject: reject };
window.webkit.messageHandlers.app.postMessage({
action: "saveFile",
callbackId: callbackId,
content: content,
fileName: fileName
});
});
},
readFile: function(filePath) {
return new Promise((resolve, reject) => {
const callbackId = 'callback_' + Math.random().toString(36).substr(2, 9);
window[callbackId] = { resolve: resolve, reject: reject };
window.webkit.messageHandlers.app.postMessage({
action: "readFile",
callbackId: callbackId,
filePath: filePath
});
});
},
readFileAsDataURL: function(filePath) {
return new Promise((resolve, reject) => {
const callbackId = 'callback_' + Math.random().toString(36).substr(2, 9);
window[callbackId] = { resolve: resolve, reject: reject };
window.webkit.messageHandlers.app.postMessage({
action: "readFileAsDataURL",
callbackId: callbackId,
filePath: filePath
});
});
},
writeLine: function(text) {
window.webkit.messageHandlers.app.postMessage({ action: "writeLine", text: text });
}
};
// Set initial theme class on document
document.addEventListener('DOMContentLoaded', function() {
document.documentElement.setAttribute('data-theme', window.app.theme);
document.documentElement.classList.toggle('dark', window.app.theme === 'dark');
});
// Listen for theme changes
window.addEventListener('themechange', function(event) {
window.app.theme = event.detail.theme;
document.documentElement.setAttribute('data-theme', event.detail.theme);
document.documentElement.classList.toggle('dark', event.detail.theme === 'dark');
});
""",
injectionTime: .atDocumentStart,
forMainFrameOnly: true
)
userContentController.addUserScript(envScript)
userContentController.addUserScript(cssInjectionScript)
userContentController.addUserScript(appScript)
}
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
if message.name == "app" {
if let messageBody = message.body as? [String: Any] {
let action = messageBody["action"] as? String ?? "unknown"
switch action {
case "finish":
appFinish(messageBody["message"] as? String ?? "")
case "setSize":
if let width = messageBody["width"] as? CGFloat, let height = messageBody["height"] as? CGFloat {
appSetSize(width, height)
}
case "setFullscreen":
appSetFullscreen(messageBody["enabled"] as? Bool ?? false)
case "setFloating":
appSetFloating(messageBody["enabled"] as? Bool ?? false)
case "setTitle":
if let title = messageBody["title"] as? String {
appSetTitle(title)
}
case "selectFolder":
if let callbackId = messageBody["callbackId"] as? String {
appSelectFolder(callbackId: callbackId)
}
case "selectFile":
if let callbackId = messageBody["callbackId"] as? String {
appSelectFile(callbackId: callbackId, options: messageBody["options"] as? [String: Any] ?? [:])
}
case "saveFile":
if let callbackId = messageBody["callbackId"] as? String {
appSaveFile(callbackId: callbackId,
content: messageBody["content"] as? String ?? "",
fileName: messageBody["fileName"] as? String)
}
case "revealInFinder":
if let path = messageBody["path"] as? String {
appRevealInFinder(path: path)
}
case "readFile":
if let callbackId = messageBody["callbackId"] as? String,
let filePath = messageBody["filePath"] as? String {
appReadFile(callbackId: callbackId, filePath: filePath, asDataURL: false)
}
case "readFileAsDataURL":
if let callbackId = messageBody["callbackId"] as? String,
let filePath = messageBody["filePath"] as? String {
appReadFile(callbackId: callbackId, filePath: filePath, asDataURL: true)
}
case "writeLine":
if let text = messageBody["text"] as? String {
appWriteLine(text)
}
default:
logError("Unknown action: \(action)")
}
}
}
}
func appSelectFolder(callbackId: String) {
let openPanel = NSOpenPanel()
openPanel.canChooseDirectories = true
openPanel.canChooseFiles = false
openPanel.allowsMultipleSelection = false
openPanel.level = .floating + 1
let response = openPanel.runModal()
self.handleFileSelection(callbackId: callbackId, response: response, panel: openPanel)
}
func appSelectFile(callbackId: String, options: [String: Any]) {
let openPanel = NSOpenPanel()
openPanel.canChooseDirectories = options["canChooseDirectories"] as? Bool ?? false
openPanel.canChooseFiles = options["canChooseFiles"] as? Bool ?? true
openPanel.allowsMultipleSelection = options["allowsMultipleSelection"] as? Bool ?? false
if let allowedTypes = options["allowedFileTypes"] as? [String] {
if #available(macOS 11.0, *) {
let types = allowedTypes.compactMap { UTType(filenameExtension: $0) }
openPanel.allowedContentTypes = types
} else {
openPanel.allowedFileTypes = allowedTypes
}
}
openPanel.level = .floating + 1
let response = openPanel.runModal()
self.handleFileSelection(callbackId: callbackId, response: response, panel: openPanel)
}
private func handleFileSelection(callbackId: String, response: NSApplication.ModalResponse, panel: NSOpenPanel) {
guard let webView = self.webView else { return }
if response == .OK {
let paths = panel.urls.map { $0.path }
let result: Any = (panel.allowsMultipleSelection) ? paths : (paths.first ?? "")
do {
let jsonData = try JSONSerialization.data(withJSONObject: [result], options: [])
guard let jsonArrayString = String(data: jsonData, encoding: .utf8) else { return }
let jsonString = String(jsonArrayString.dropFirst().dropLast())
let jsCallback = """
(function() {
const cb = window['\(callbackId)'];
if (cb) {
cb.resolve(\(jsonString));
delete window['\(callbackId)'];
}
})();
"""
DispatchQueue.main.async {
webView.evaluateJavaScript(jsCallback) { _, error in
if let error = error {
logError("JS evaluation error: \(error.localizedDescription)")
}
}
}
} catch {
logError("JSON serialization error: \(error.localizedDescription)")
}
} else {
let jsCallback = "if(window['\(callbackId)']) { window['\(callbackId)'].reject('Cancelled'); delete window['\(callbackId)']; }"
DispatchQueue.main.async {
webView.evaluateJavaScript(jsCallback, completionHandler: nil)
}
}
}
func appSaveFile(callbackId: String, content: String, fileName: String?) {
let savePanel = NSSavePanel()
if let fileName = fileName {
savePanel.nameFieldStringValue = fileName
}
savePanel.level = .floating + 1
let response = savePanel.runModal()
guard let webView = self.webView else { return }
if response == .OK, let url = savePanel.url {
do {
try content.write(to: url, atomically: true, encoding: .utf8)
let jsonData = try JSONSerialization.data(withJSONObject: [url.path], options: [])
let jsonPath = String(data: jsonData, encoding: .utf8)?.dropFirst().dropLast() ?? "\"\""
let jsCallback = """
(function() {
const cb = window['\(callbackId)'];
if (cb) {
cb.resolve(\(jsonPath));
delete window['\(callbackId)'];
}
})();
"""
webView.evaluateJavaScript(jsCallback)
} catch {
let errString = error.localizedDescription
let jsonData = (try? JSONSerialization.data(withJSONObject: [errString], options: [])) ?? Data()
let jsonErr = String(data: jsonData, encoding: .utf8)?.dropFirst().dropLast() ?? "\"Error\""
let jsCallback = "window['\(callbackId)'].reject(\(jsonErr)); delete window['\(callbackId)'];"
webView.evaluateJavaScript(jsCallback)
}
} else {
let jsCallback = "if(window['\(callbackId)']) { window['\(callbackId)'].reject('Cancelled'); delete window['\(callbackId)']; }"
webView.evaluateJavaScript(jsCallback)
}
}
func appRevealInFinder(path: String) {
NSWorkspace.shared.selectFile(path, inFileViewerRootedAtPath: "")
}
func appWriteLine(_ text: String) {
print(text)
}
func applicationWillTerminate(_ aNotification: Notification) {
themeObserver?.invalidate()
themeObserver = nil
if let closeMessage = closeString {
print(closeMessage)
}
}
// JavaScript binding function
func appFinish(_ message: String) {
closeString = message
NSApplication.shared.terminate(nil)
}
func appSetSize(_ width: CGFloat, _ height: CGFloat) {