Repository navigation
Expand file tree
/
Copy pathLGPlatformPresentation.swift
More file actions
467 lines (425 loc) · 17.5 KB
/
Copy pathLGPlatformPresentation.swift
File metadata and controls
467 lines (425 loc) · 17.5 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
import Observation
import SwiftUI
import LogseqModel
import PhotosUI
import UniformTypeIdentifiers
#if os(iOS)
import QuickLook
import UIKit
#endif
public enum LGAttachmentService: String, CaseIterable, Sendable {
case files
case camera
case photos
case audio
#if os(iOS)
case quickPhotos = "quick-photos"
#endif
}
extension PhotosPickerItem {
func loadImageForAttachment() async throws -> (Data, String) {
guard let data = try await loadTransferable(type: Data.self) else {
throw CocoaError(.fileReadUnknown)
}
return (data, supportedContentTypes.first?.preferredFilenameExtension ?? "jpg")
}
}
struct LGAttachmentRequest {
let id: UUID
let targetBlockID: String?
}
@MainActor
@Observable
public final class LGPlatformPresentationCoordinator {
public var journalCalendarPresented = false
public var graphDownloadProgress: LogseqGraphDownloadProgress?
public private(set) var attachmentService: LGAttachmentService?
public private(set) var attachmentTargetBlockID: String?
public private(set) var attachmentRequestID = UUID()
var attachmentRequest: LGAttachmentRequest {
LGAttachmentRequest(id: attachmentRequestID, targetBlockID: attachmentTargetBlockID)
}
public private(set) var pendingDeletionBlockIDs: [String] = []
public init() {
}
@discardableResult
public func presentJournalCalendar() -> Bool {
journalCalendarPresented = true
return true
}
@discardableResult
public func presentAttachment(
_ rawValue: String,
targetBlockID: String? = nil
) -> Bool {
guard let service = LGAttachmentService(rawValue: rawValue) else {
return false
}
attachmentRequestID = UUID()
attachmentService = service
attachmentTargetBlockID = targetBlockID
return true
}
public func dismissAttachment(requestID: UUID? = nil) {
guard requestID == nil || requestID == attachmentRequestID else { return }
attachmentService = nil
}
public func completeAttachment(requestID: UUID? = nil) {
guard requestID == nil || requestID == attachmentRequestID else { return }
attachmentService = nil
attachmentTargetBlockID = nil
}
public func confirmDeletion(of blockIDs: [String]) {
pendingDeletionBlockIDs = blockIDs
}
public func dismissDeletion() {
pendingDeletionBlockIDs = []
}
#if os(iOS)
private(set) var taskDateSheet: LGTaskDateSheetRequest?
var shortcutCameraGraph: LogseqJournalShortcutCapture.Graph?
func presentTaskDateSheet(_ request: LGTaskDateSheetRequest) {
// Patches may disable animation while applying model changes. Let the
// persistent sheet host use the system presentation transaction.
withTransaction(Transaction()) { taskDateSheet = request }
}
func dismissTaskDateSheet(_ request: LGTaskDateSheetRequest) {
guard taskDateSheet === request else { return }
withTransaction(Transaction()) { taskDateSheet = nil }
}
func taskDateSheetDismissedByUser() {
guard let request = taskDateSheet else { return }
dismissTaskDateSheet(request)
try? request.context.emit(name: "dismiss", values: [:])
}
@discardableResult
public func presentPageShare(_ payload: LGPageSharePayload) -> Bool {
return presentShareSheet(
NodeSharePayload(
text: payload.text,
localAssetPaths: payload.localAssetPaths
).items
)
}
@discardableResult
public func presentFile(_ url: URL) -> Bool {
guard FileManager.default.fileExists(atPath: url.path) else { return false }
return presentShareSheet([url])
}
/// Presents the activity sheet on the topmost presented controller so it
/// can appear above an already-presented LUI sheet (e.g. Settings); a
/// root-level `.sheet` would queue behind it with no visible feedback.
private func presentShareSheet(_ items: [Any]) -> Bool {
guard let presenter = Self.topmostPresenter() else { return false }
let controller = UIActivityViewController(
activityItems: items,
applicationActivities: nil
)
if let popover = controller.popoverPresentationController {
popover.sourceView = presenter.view
popover.sourceRect = CGRect(
x: presenter.view.bounds.midX,
y: presenter.view.bounds.midY,
width: 0,
height: 0
)
}
presenter.present(controller, animated: true)
return true
}
private static func topmostPresenter() -> UIViewController? {
let windows = UIApplication.shared.connectedScenes
.compactMap { $0 as? UIWindowScene }
.flatMap { $0.windows }
let root = windows.first(where: { $0.isKeyWindow })?.rootViewController
?? windows.first?.rootViewController
var top = root
while let presented = top?.presentedViewController {
top = presented
}
return top
}
#endif
}
#if os(iOS)
extension EnvironmentValues {
@Entry var lgPlatformPresentation: LGPlatformPresentationCoordinator? = nil
}
#endif
#if os(iOS)
private struct LGSheetSurface: ViewModifier {
@Environment(\.colorScheme) private var colorScheme
@Environment(\.logseqDarkTheme) private var darkTheme
func body(content: Content) -> some View {
let dark = colorScheme == .dark
let background = LogseqThemePolicy.sheetBackground(isDark: dark, darkTheme: darkTheme)
content
.background(background.ignoresSafeArea())
.presentationBackground(background)
.tint(LogseqThemePolicy.accent)
}
}
private extension View {
func lgCalendarSheet() -> some View {
modifier(LGSheetSurface())
.presentationDetents([.height(460)])
}
}
struct LGJournalCalendar: View {
let onSelect: (Int) -> Void
@Environment(\.dismiss) private var dismiss
@State private var date = Date()
@State private var selected = false
var body: some View {
NavigationStack {
DatePicker("Choose a date", selection: $date, displayedComponents: .date)
.datePickerStyle(.graphical)
.labelsHidden()
.padding(.horizontal, 16)
.accessibilityIdentifier("picker.journal-date")
.onChange(of: date) { _, value in select(value) }
.navigationTitle("Go to journal")
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItem(placement: .cancellationAction) {
Button("Cancel") { dismiss() }
.foregroundStyle(.primary)
}
ToolbarItem(placement: .confirmationAction) {
Button("Today") { select(Date()) }
.foregroundStyle(.primary)
.accessibilityIdentifier("button.journal-calendar.today")
}
}
}
}
private func select(_ date: Date) {
guard !selected else { return }
selected = true
let parts = Calendar(identifier: .gregorian).dateComponents([.year, .month, .day], from: date)
onSelect(parts.year! * 10000 + parts.month! * 100 + parts.day!)
}
}
#endif
struct LGPlatformPresentationHost: ViewModifier {
@Bindable var coordinator: LGPlatformPresentationCoordinator
let confirmOutlinerDelete: @MainActor () -> Void
let stageAsset: @MainActor (String) throws -> Void
var openJournal: @MainActor (Int) async throws -> Void = { _ in }
@State private var selectedPhotoItems: [PhotosPickerItem] = []
func body(content: Content) -> some View {
let request = coordinator.attachmentRequest
return content
.fileImporter(
isPresented: presentationBinding(for: .files),
allowedContentTypes: [.image, .audio, .data],
allowsMultipleSelection: true,
onCompletion: { importFiles($0, request: request) }
)
#if !os(iOS)
.photosPicker(
isPresented: presentationBinding(for: .photos),
selection: $selectedPhotoItems,
maxSelectionCount: 20,
matching: .images
)
.onChange(of: selectedPhotoItems) { _, items in
importPhotos(items)
}
#endif
.background {
Color.clear
.alert(deletionTitle, isPresented: deletionBinding) {
Button("Delete", role: .destructive) {
confirmOutlinerDelete()
coordinator.dismissDeletion()
}
Button("Cancel", role: .cancel) {
coordinator.dismissDeletion()
}
} message: {
Text("This deletes the block and all of its children. Pages use Recycle instead.")
}
.tint(.primary)
}
#if os(iOS)
.environment(\.lgPlatformPresentation, coordinator)
.onChange(of: coordinator.journalCalendarPresented || coordinator.graphDownloadProgress != nil
|| coordinator.taskDateSheet != nil || coordinator.attachmentService != nil
|| coordinator.shortcutCameraGraph != nil
|| !coordinator.pendingDeletionBlockIDs.isEmpty,
initial: true) { _, open in
LogseqCrashReporting.presentation(.platform, open: open)
}
.sheet(item: Binding(
get: { coordinator.graphDownloadProgress },
set: { _ in }
)) { _ in
GraphDownloadProgressView(coordinator: coordinator)
.modifier(LGSheetSurface())
.presentationDetents([.height(260)])
.interactiveDismissDisabled()
}
.sheet(isPresented: $coordinator.journalCalendarPresented) {
LGJournalCalendar { day in
coordinator.journalCalendarPresented = false
Task {
do { try await openJournal(day) }
catch { logger.error("Could not open journal: \(error.localizedDescription)") }
}
}
.lgCalendarSheet()
}
.fullScreenCover(item: $coordinator.shortcutCameraGraph) { graph in
LGJournalShortcutCamera(graph: graph)
}
.sheet(item: Binding(
get: { coordinator.taskDateSheet },
set: { if $0 == nil { coordinator.taskDateSheetDismissedByUser() } }
)) { request in
LGTaskDateSheet(request: request)
.modifier(LGSheetSurface())
.presentationDetents([.custom(LGTaskDateSheetDetent.self)])
.presentationContentInteraction(.scrolls)
}
.sheet(isPresented: mediaPanelBinding) {
let request = coordinator.attachmentRequest
let target = request.targetBlockID
VStack(spacing: 0) {
LGMediaPanel(initialService: coordinator.attachmentService ?? .photos) { items in
importPhotos(items, closeWhenFinished: false, request: request)
} onCapture: { data in
importCapturedData(data, targetBlockID: target)
} onPhotoData: { data, fileExtension in
importCapturedData(data, targetBlockID: target,
title: "Photo-\(UUID().uuidString).\(fileExtension)")
}
}
.modifier(LGSheetSurface())
.presentationDetents([.fraction(0.58), .large])
.presentationDragIndicator(.hidden)
.presentationCornerRadius(32)
}
.sheet(isPresented: presentationBinding(for: .quickPhotos)) {
LGQuickPhotoPicker { data, fileExtension in
try await importPhoto(data, fileExtension: fileExtension, targetBlockID: request.targetBlockID)
coordinator.completeAttachment(requestID: request.id)
}
.id(request.id)
.modifier(LGSheetSurface())
.presentationDetents([.height(164)])
.presentationDragIndicator(.hidden)
}
.sheet(isPresented: presentationBinding(for: .audio)) {
AudioRecorderSheet(
targetBlockID: request.targetBlockID
) { asset, targetBlockID, transcript in
try addImportedAsset(LGImportedAsset(
title: asset.title, assetType: AudioRecordingPolicy.fileExtension,
size: asset.size, checksum: asset.checksum, path: asset.path
), targetBlockID: targetBlockID, transcript: transcript)
coordinator.completeAttachment(requestID: request.id)
}
.id(request.id)
.modifier(LGSheetSurface())
}
#endif
}
var mediaPanelBinding: Binding<Bool> {
let request = coordinator.attachmentRequest
return Binding(
get: {
coordinator.attachmentRequestID == request.id &&
(coordinator.attachmentService == .camera || coordinator.attachmentService == .photos)
},
set: { shown in
if !shown, coordinator.attachmentService == .camera || coordinator.attachmentService == .photos {
coordinator.completeAttachment(requestID: request.id)
}
}
)
}
func presentationBinding(for service: LGAttachmentService) -> Binding<Bool> {
let request = coordinator.attachmentRequest
return Binding(
get: { coordinator.attachmentRequestID == request.id && coordinator.attachmentService == service },
set: { shown in
if !shown, coordinator.attachmentService == service {
coordinator.dismissAttachment(requestID: request.id)
}
}
)
}
private var deletionBinding: Binding<Bool> {
Binding(
get: { !coordinator.pendingDeletionBlockIDs.isEmpty },
set: { presented in
if !presented {
coordinator.dismissDeletion()
}
}
)
}
private var deletionTitle: String {
coordinator.pendingDeletionBlockIDs.count > 1 ? "Delete blocks?" : "Delete block?"
}
func importFiles(_ result: Result<[URL], Error>, request: LGAttachmentRequest? = nil) {
let request = request ?? coordinator.attachmentRequest
guard case .success(let urls) = result else {
coordinator.completeAttachment(requestID: request.id)
return
}
Task {
for url in urls {
do {
try addImportedAsset(try await LGAssetImporter.persist(url), targetBlockID: request.targetBlockID)
} catch {
logger.error("Asset import failed: \(String(describing: error))")
}
}
coordinator.completeAttachment(requestID: request.id)
}
}
private func importPhotos(_ items: [PhotosPickerItem], closeWhenFinished: Bool = true,
request: LGAttachmentRequest? = nil) {
guard !items.isEmpty else { return }
selectedPhotoItems = []
let request = request ?? coordinator.attachmentRequest
Task {
for item in items {
do {
let (data, fileExtension) = try await item.loadImageForAttachment()
try await importPhoto(data, fileExtension: fileExtension, targetBlockID: request.targetBlockID)
} catch {
logger.error("Photo import failed: \(String(describing: error))")
}
}
if closeWhenFinished { coordinator.completeAttachment(requestID: request.id) }
}
}
private func importPhoto(_ data: Data, fileExtension: String, targetBlockID: String?) async throws {
let title = "Photo-\(UUID().uuidString).\(fileExtension)"
let asset = try await LGAssetImporter.persist(data: data, title: title)
try addImportedAsset(asset, targetBlockID: targetBlockID)
}
#if os(iOS)
private func importCapturedData(_ data: Data, targetBlockID: String?,
title: String = "Camera-\(UUID().uuidString).jpg") {
Task {
do {
try addImportedAsset(
try await LGAssetImporter.persist(data: data, title: title),
targetBlockID: targetBlockID
)
} catch {
logger.error("Camera import failed: \(String(describing: error))")
}
}
}
#endif
private func addImportedAsset(_ asset: LGImportedAsset, targetBlockID: String? = nil, transcript: String? = nil) throws {
let payload = LGStagedAssetPayload(asset, targetBlockID: targetBlockID, transcript: transcript)
let data = try JSONEncoder().encode(payload)
try stageAsset(String(decoding: data, as: UTF8.self))
}
}