Branchwell

Jotley / app · jotley.ai / iOS / Views / ShareSheet.swift

Raw 6.2 KB on c22c50f3614b055549c1ecbf54af0165e0bc8df1
1import SwiftUI
2import UIKit
3import CoreData
4
5struct LocalSharePayload: Identifiable {
6 let id = UUID()
7 let items: [Any]
8}
9
10/// Retains the original local file export formats used by the note share menu.
11@MainActor enum LocalNoteExport {
12 enum Format { case plainText, markdown, summary, transcript }
13 /// Call once at launch, before any share sheet can own a temporary export.
14 /// Completed user exports live outside this temporary namespace.
15 static func cleanupStaleExports(temporaryRoot: URL = FileManager.default.temporaryDirectory) throws {
16 let prefix = "JotleyExport-"
17 for directory in try FileManager.default.contentsOfDirectory(at: temporaryRoot,
18 includingPropertiesForKeys: [.isDirectoryKey, .isSymbolicLinkKey]) {
19 guard directory.lastPathComponent.hasPrefix(prefix),
20 UUID(uuidString: String(directory.lastPathComponent.dropFirst(prefix.count))) != nil else { continue }
21 let kind = try directory.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey])
22 guard kind.isDirectory == true, kind.isSymbolicLink != true else { continue }
23 try FileManager.default.removeItem(at: directory)
24 }
25 }
26 static func content(note: Note, format: Format) -> String {
27 let trimmedTitle = (note.title ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
28 let title = trimmedTitle.isEmpty ? "Untitled Note" : trimmedTitle
29 let summary = (note.summary ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
30 let transcript = (note.transcription ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
31 let formatter = DateFormatter(); formatter.dateStyle = .long; formatter.timeStyle = .short
32 let date = note.timestamp.map { formatter.string(from: $0) }
33 if format == .summary || format == .transcript {
34 let section = format == .summary ? "Summary" : "Transcript"
35 let body = format == .summary ? summary : transcript
36 return "# \(title) - \(section)\n\n" + (date.map { "*Exported: \($0)*\n\n" } ?? "") + (body.isEmpty ? "*No \(section.lowercased()) available*\n" : "\(body)\n")
37 }
38 if format == .plainText {
39 var output = "\(title)\n" + String(repeating: "=", count: title.count) + "\n\n"
40 if let date { output += "Created: \(date)\n\n" }
41 if !note.tagNames.isEmpty { output += "Tags: \(note.tagNames.joined(separator: ", "))\n\n" }
42 if !summary.isEmpty { output += "SUMMARY\n-------\n\(summary)\n\n" }
43 if !transcript.isEmpty { output += "TRANSCRIPT\n----------\n\(transcript)\n" }
44 return output
45 }
46 var output = "# \(title)\n\n"
47 if let date { output += "*Created: \(date)*\n\n" }
48 if !note.tagNames.isEmpty { output += "**Tags:** \(note.tagNames.map { "#\($0)" }.joined(separator: " "))\n\n" }
49 if !summary.isEmpty { output += "## Summary\n\n\(summary)\n\n" }
50 if !transcript.isEmpty { output += "## Transcript\n\n\(transcript)\n" }
51 return output
52 }
53 static func file(note: Note, format: Format, temporaryRoot: URL = FileManager.default.temporaryDirectory) throws -> URL {
54 let suffix = format == .summary ? " - Summary" : format == .transcript ? " - Transcript" : ""
55 let url = try exportURL(note: note, suffix: suffix, extension: format == .plainText ? "txt" : "md", temporaryRoot: temporaryRoot)
56 do { try content(note: note, format: format).write(to: url, atomically: true, encoding: .utf8); return url }
57 catch { try? FileManager.default.removeItem(at: url.deletingLastPathComponent()); throw error }
58 }
59 /// The summary rendered in Jotley's structured layout, ready to share.
60 static func summaryPDF(note: Note, temporaryRoot: URL = FileManager.default.temporaryDirectory) throws -> URL {
61 let url = try exportURL(note: note, suffix: " - Summary", extension: "pdf", temporaryRoot: temporaryRoot)
62 let title = (note.title ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
63 do { try SummaryPDF.write(title: title.isEmpty ? "Untitled Note" : title, date: note.timestamp, markdown: note.summary ?? "", to: url); return url }
64 catch { try? FileManager.default.removeItem(at: url.deletingLastPathComponent()); throw error }
65 }
66 private static func exportURL(note: Note, suffix: String, extension ext: String, temporaryRoot: URL) throws -> URL {
67 guard note.managedObjectContext != nil, !note.isDeleted else { throw LocalError.message("This note is unavailable.") }
68 let title = (note.title ?? "Untitled").trimmingCharacters(in: .whitespacesAndNewlines)
69 let invalid = CharacterSet(charactersIn: "/\\?%*|\"<>:").union(.controlCharacters)
70 // Keep names bounded while preserving Unicode; a unique directory avoids collisions.
71 var safe = ""; var bytes = 0
72 for scalar in title.components(separatedBy: invalid).joined(separator: "-").unicodeScalars {
73 let size = String(scalar).utf8.count
74 if bytes + size > 160 { break }
75 safe.unicodeScalars.append(scalar); bytes += size
76 }
77 let name = safe.isEmpty || safe == "." || safe == ".." ? "Untitled" : safe
78 let directory = temporaryRoot.appendingPathComponent("JotleyExport-\(UUID().uuidString)", isDirectory: true)
79 try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
80 return directory.appendingPathComponent(name + suffix + "." + ext)
81 }
82}
83
84/// A SwiftUI wrapper for UIActivityViewController to present the system share sheet.
85struct ShareSheet: UIViewControllerRepresentable {
86 let activityItems: [Any]
87 var applicationActivities: [UIActivity]? = nil
88 var excludedActivityTypes: [UIActivity.ActivityType]? = nil
89
90 func makeUIViewController(context: Context) -> UIActivityViewController {
91 let controller = UIActivityViewController(
92 activityItems: activityItems,
93 applicationActivities: applicationActivities
94 )
95 controller.excludedActivityTypes = excludedActivityTypes
96 return controller
97 }
98
99 func updateUIViewController(_ uiViewController: UIActivityViewController, context: Context) {
100 // No updates needed
101 }
102}