ApplyTempPresetIntent.swift 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import AppIntents
  2. import Foundation
  3. 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. @Parameter(title: "Preset") var preset: TempPreset?
  9. @Parameter(
  10. title: "Confirm Before applying",
  11. description: "If toggled, you will need to confirm before applying",
  12. default: true
  13. ) var confirmBeforeApplying: Bool
  14. static var parameterSummary: some ParameterSummary {
  15. When(\ApplyTempPresetIntent.$confirmBeforeApplying, .equalTo, true, {
  16. Summary("Applying \(\.$preset)") {
  17. \.$confirmBeforeApplying
  18. }
  19. }, otherwise: {
  20. Summary("Immediately applying \(\.$preset)") {
  21. \.$confirmBeforeApplying
  22. }
  23. })
  24. }
  25. private func decimalToTimeFormattedString(decimal: Decimal) -> String {
  26. let timeInterval = TimeInterval(decimal * 60) // seconds
  27. let formatter = DateComponentsFormatter()
  28. formatter.allowedUnits = [.hour, .minute]
  29. formatter.unitsStyle = .brief // example: 1h 10 min
  30. return formatter.string(from: timeInterval) ?? ""
  31. }
  32. @MainActor func perform() async throws -> some ProvidesDialog {
  33. do {
  34. let intentRequest = TempPresetsIntentRequest()
  35. let presetToApply: TempPreset
  36. if let preset = preset {
  37. presetToApply = preset
  38. } else {
  39. presetToApply = try await $preset.requestDisambiguation(
  40. among: intentRequest.fetchAndProcessTempTargets(),
  41. dialog: "Select Temporary Target"
  42. )
  43. }
  44. let displayName: String = presetToApply.name
  45. if confirmBeforeApplying {
  46. try await requestConfirmation(
  47. result: .result(dialog: "Confirm to apply Temporary Target '\(displayName)'")
  48. )
  49. }
  50. if await intentRequest.enactTempTarget(presetToApply) {
  51. return .result(
  52. dialog: IntentDialog(
  53. LocalizedStringResource(
  54. "Temporary Target '\(presetToApply.name)' applied",
  55. table: "ShortcutsDetail"
  56. )
  57. )
  58. )
  59. } else {
  60. return .result(
  61. dialog: IntentDialog(
  62. LocalizedStringResource(
  63. "Temporary Target '\(presetToApply.name)' failed",
  64. table: "ShortcutsDetail"
  65. )
  66. )
  67. )
  68. }
  69. } catch {
  70. throw error
  71. }
  72. }
  73. }