SPB Git

Repository Public

TaskEntity.swift 5.2 KB 124 lines swift

1// SP Notes iOS2// File: WidgetShared/TaskEntity.swift3// Description: A task as the system sees it (Shortcuts, Siri, widget buttons), its query over the open tasks of the local copy,4//              and the two intents the widgets run: « Terminer une tâche » (completes without opening the app) and the opening5//              of the capture sheet in a given mode. Compiled into the app and into the widget extension.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import AppIntents10import Foundation11import os12import WidgetKit1314struct TaskEntity: AppEntity, Identifiable, Sendable {15    static let typeDisplayRepresentation = TypeDisplayRepresentation(name: "Tâche")16    static let defaultQuery = TaskEntityQuery()1718    var id: String19    @Property(title: "Titre") var title: String20    @Property(title: "Échéance") var dueAt: Date?21    @Property(title: "Note") var noteTitle: String?2223    init(id: String, title: String, dueAt: Date? = nil, noteTitle: String? = nil) {24        self.id = id25        self.title = title26        self.dueAt = dueAt27        self.noteTitle = noteTitle28    }2930    init(_ task: WidgetTask) { self.init(id: task.id, title: task.title, dueAt: task.dueAt, noteTitle: task.noteTitle) }3132    var displayRepresentation: DisplayRepresentation {33        if let noteTitle, !noteTitle.isEmpty { return DisplayRepresentation(title: "\(title)", subtitle: "\(noteTitle)") }34        return DisplayRepresentation(title: "\(title)")35    }36}3738/// Open tasks only: a finished task is not something to pick.39struct TaskEntityQuery: EntityStringQuery {40    func entities(for identifiers: [String]) async throws -> [TaskEntity] {41        let wanted = Set(identifiers)42        return await WidgetDataProvider().openTasks(limit: 1_000).filter { wanted.contains($0.id) }.map(TaskEntity.init)43    }4445    func entities(matching string: String) async throws -> [TaskEntity] {46        let needle = string.folding(options: [.diacriticInsensitive, .caseInsensitive], locale: nil)47        return await WidgetDataProvider().openTasks(limit: 1_000)48            .filter { $0.title.folding(options: [.diacriticInsensitive, .caseInsensitive], locale: nil).contains(needle) }49            .prefix(25).map(TaskEntity.init)50    }5152    func suggestedEntities() async throws -> [TaskEntity] {53        await WidgetDataProvider().openTasks(limit: 25).map(TaskEntity.init)54    }55}5657/// Identifiers of the widgets (shared with the app, which reloads them by kind).58enum WidgetKinds {59    static let recent = "ai.spboucher.spnotes.widget.recent"60    static let pinned = "ai.spboucher.spnotes.widget.pinned"61    static let new = "ai.spboucher.spnotes.widget.new"62    static let note = "ai.spboucher.spnotes.widget.note"63    static let tasks = "ai.spboucher.spnotes.widget.tasks"64}6566struct CompleteTaskIntent: AppIntent {67    static let title: LocalizedStringResource = "Terminer une tâche"68    static let description = IntentDescription("Marque une tâche comme terminée, sans ouvrir l’app.", categoryName: "Tâches")69    static let openAppWhenRun = false7071    @Parameter(title: "Tâche") var task: TaskEntity7273    static var parameterSummary: some ParameterSummary {74        Summary("Terminer \(\.$task)")75    }7677    init() {}78    init(task: TaskEntity) { self.task = task }79    init(_ task: WidgetTask) { self.task = TaskEntity(task) }8081    func perform() async throws -> some IntentResult & ProvidesDialog {82        let outcome = await SharedTaskActions.setDone(taskId: task.id)83        WidgetCenter.shared.reloadTimelines(ofKind: WidgetKinds.tasks)84        return .result(dialog: Self.dialog(for: outcome, title: task.title))85    }8687    static func dialog(for outcome: SharedTaskActions.Outcome, title: String) -> IntentDialog {88        switch outcome {89        case .done: return "« \(title) » est terminée."90        case .locked: return "SP Notes est verrouillé. Ouvre l’app pour terminer cette tâche."91        case .unavailable: return "Ouvre SP Notes une fois, puis réessaie."92        case .notFound: return "Cette tâche n’existe plus."93        case .failed: return "La tâche n’a pas pu être modifiée."94        }95    }96}9798/// Opening something in the app from a widget button (a small widget has one link only: its buttons are intents).99/// The app installs the handler; the system brings the app forward (`openAppWhenRun`) and runs the intent there.100enum SystemOpen {101    typealias Handler = @Sendable (URL) async -> Void102    private static let handler = OSAllocatedUnfairLock<Handler?>(initialState: nil)103    static func useApp(_ open: @escaping Handler) { handler.withLock { $0 = open } }104    static func open(_ url: URL) async { await handler.withLock({ $0 })?(url) }105}106107struct OpenCaptureIntent: AppIntent {108    static let title: LocalizedStringResource = "Capturer"109    static let description = IntentDescription("Ouvre la capture rapide de SP Notes.", categoryName: "Capture")110    static let openAppWhenRun = true111    static let isDiscoverable = false112113    /// A capture kind of `spnotes://capture?kind=…` (empty = the default capture).114    @Parameter(title: "Mode") var kind: String?115116    init() {}117    init(kind: String?) { self.kind = kind }118119    func perform() async throws -> some IntentResult {120        await SystemOpen.open(SystemLinks.capture(kind: kind))121        return .result()122    }123}124
Files main
Menu

Theme