ApplyTempPresetIntent.swift 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import AppIntents
  2. import Foundation
  3. @available(iOS 16.0, *) struct ApplyTempPresetIntent: AppIntent {
  4. // Title of the action in the Shortcuts app
  5. static var title: LocalizedStringResource = "Apply a temporary target"
  6. // Description of the action in the Shortcuts app
  7. static var description = IntentDescription("Enable a temporary target")
  8. internal var intentRequest: TempPresetsIntentRequest
  9. init() {
  10. intentRequest = TempPresetsIntentRequest()
  11. }
  12. @Parameter(title: "Preset") var preset: tempPreset?
  13. @Parameter(
  14. title: "Confirm Before applying",
  15. description: "If toggled, you will need to confirm before applying",
  16. default: true
  17. ) var confirmBeforeApplying: Bool
  18. static var parameterSummary: some ParameterSummary {
  19. When(\ApplyTempPresetIntent.$confirmBeforeApplying, .equalTo, true, {
  20. Summary("Applying \(\.$preset)") {
  21. \.$confirmBeforeApplying
  22. }
  23. }, otherwise: {
  24. Summary("Immediately applying \(\.$preset)") {
  25. \.$confirmBeforeApplying
  26. }
  27. })
  28. }
  29. private func decimalToTimeFormattedString(decimal: Decimal) -> String {
  30. let timeInterval = TimeInterval(decimal * 60) // seconds
  31. let formatter = DateComponentsFormatter()
  32. formatter.allowedUnits = [.hour, .minute]
  33. formatter.unitsStyle = .brief // example: 1h 10 min
  34. return formatter.string(from: timeInterval) ?? ""
  35. }
  36. @MainActor func perform() async throws -> some ProvidesDialog {
  37. do {
  38. let presetToApply: tempPreset
  39. if let preset = preset {
  40. presetToApply = preset
  41. } else {
  42. presetToApply = try await $preset.requestDisambiguation(
  43. among: intentRequest.fetchAll(),
  44. dialog: "Select Temporary Target"
  45. )
  46. }
  47. let displayName: String = presetToApply.name
  48. if confirmBeforeApplying {
  49. try await requestConfirmation(
  50. result: .result(dialog: "Confirm to apply temporary target '\(displayName)'")
  51. )
  52. }
  53. // TODO: enact the temp target
  54. let tempTarget = try intentRequest.findTempTarget(presetToApply)
  55. let finalTempTargetApply = try intentRequest.enactTempTarget(tempTarget)
  56. let formattedTime = decimalToTimeFormattedString(decimal: finalTempTargetApply.duration)
  57. let displayDetail: String =
  58. "Target '\(finalTempTargetApply.displayName)' applied for \(formattedTime)"
  59. return .result(
  60. dialog: IntentDialog(stringLiteral: displayDetail)
  61. )
  62. } catch {
  63. throw error
  64. }
  65. }
  66. }