Repository Public
1// SP Notes iOS2// File: Features/Editor/EditorDropHandler.swift3// Description: Drag and drop onto the editor: pictures, PDFs and other files dropped from another app are attached to the note and4// inserted where they were dropped. Drops of plain text are left to the text view's own text drop handling.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import UIKit9import UniformTypeIdentifiers1011@MainActor12final class EditorDropHandler: NSObject, UIDropInteractionDelegate {13 weak var model: NoteEditorModel?14 private weak var textView: UITextView?15 private var interaction: UIDropInteraction?1617 /// Adds the drop interaction to the editor's text view (once).18 func install(on model: NoteEditorModel) {19 self.model = model20 let view = model.controller.textView21 guard textView !== view else { return }22 uninstall()23 let interaction = UIDropInteraction(delegate: self)24 view.addInteraction(interaction)25 self.interaction = interaction26 textView = view27 }2829 func uninstall() {30 if let interaction, let textView { textView.removeInteraction(interaction) }31 interaction = nil32 textView = nil33 }3435 /// Whether an item with these types is a file to attach (as opposed to text or a link, which the text view inserts itself).36 nonisolated static func isFile(types: [UTType]) -> Bool {37 if types.contains(where: { $0.conforms(to: .image) || $0.conforms(to: .pdf) || $0.conforms(to: .audiovisualContent) || $0.conforms(to: .archive) || $0 == .fileURL }) { return true }38 let isText = types.contains { $0.conforms(to: .text) || $0.conforms(to: .url) }39 return !isText && types.contains { $0.conforms(to: .data) }40 }4142 /// The representation to load for a file item: a picture or PDF type first, then any concrete data type.43 nonisolated static func preferredType(in types: [UTType]) -> UTType? {44 types.first { $0.conforms(to: .image) } ?? types.first { $0.conforms(to: .pdf) }45 ?? types.first { $0.conforms(to: .data) && $0 != .fileURL && !$0.conforms(to: .url) }46 ?? types.first { $0 != .fileURL }47 }4849 private static func types(of provider: NSItemProvider) -> [UTType] { provider.registeredTypeIdentifiers.compactMap { UTType($0) } }5051 // MARK: UIDropInteractionDelegate5253 func dropInteraction(_ interaction: UIDropInteraction, canHandle session: any UIDropSession) -> Bool {54 guard let textView, textView.isEditable, model != nil else { return false }55 return session.items.contains { Self.isFile(types: Self.types(of: $0.itemProvider)) }56 }5758 func dropInteraction(_ interaction: UIDropInteraction, sessionDidUpdate session: any UIDropSession) -> UIDropProposal {59 UIDropProposal(operation: .copy)60 }6162 func dropInteraction(_ interaction: UIDropInteraction, performDrop session: any UIDropSession) {63 guard let model, let textView else { return }64 // The files go where they were dropped: the caret moves to the paragraph under the finger.65 if let position = textView.closestPosition(to: session.location(in: textView)) {66 let offset = textView.offset(from: textView.beginningOfDocument, to: position)67 textView.selectedRange = model.controller.clampSelection(NSRange(location: offset, length: 0))68 }69 let providers = session.items.map(\.itemProvider)70 Task { @MainActor in71 var files: [URL] = []72 var texts: [String] = []73 var failed = 074 for (index, provider) in providers.enumerated() {75 let types = Self.types(of: provider)76 if Self.isFile(types: types) {77 if let url = await Self.loadFile(from: provider, types: types, fallbackName: "fichier-\(index + 1)") { files.append(url) } else { failed += 1 }78 } else if provider.canLoadObject(ofClass: NSString.self), let text = await Self.loadText(from: provider) {79 texts.append(text)80 }81 }82 if !texts.isEmpty { model.controller.insertText(texts.joined(separator: "\n")) }83 if !files.isEmpty {84 await model.insertFiles(files)85 files.forEach(MediaTemp.discard)86 }87 if failed > 0 {88 model.app.banner = failed == 1 ? String(localized: "Un élément déposé n’a pas pu être lu.") : String(localized: "\(failed) éléments déposés n’ont pas pu être lus.")89 }90 }91 }9293 // MARK: loading9495 private static func loadFile(from provider: NSItemProvider, types: [UTType], fallbackName: String) async -> URL? {96 guard let type = preferredType(in: types) else { return nil }97 let suggested = provider.suggestedName98 return await withCheckedContinuation { (continuation: CheckedContinuation<URL?, Never>) in99 provider.loadFileRepresentation(forTypeIdentifier: type.identifier) { url, _ in100 // The file only exists during this callback: copy it now.101 guard let url else { continuation.resume(returning: nil); return }102 let ext = url.pathExtension.isEmpty ? (type.preferredFilenameExtension ?? "") : url.pathExtension103 let base = suggested?.isEmpty == false ? suggested! : (url.deletingPathExtension().lastPathComponent.isEmpty ? fallbackName : url.deletingPathExtension().lastPathComponent)104 let name = ext.isEmpty || (base as NSString).pathExtension.lowercased() == ext.lowercased() ? base : "\(base).\(ext)"105 continuation.resume(returning: try? MediaTemp.copy(url, named: name))106 }107 }108 }109110 private static func loadText(from provider: NSItemProvider) async -> String? {111 await withCheckedContinuation { (continuation: CheckedContinuation<String?, Never>) in112 _ = provider.loadObject(ofClass: NSString.self) { object, _ in continuation.resume(returning: object as? String) }113 }114 }115}116