ApplyOverridePresetIntent.swift 3.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. import AppIntents
  2. import Foundation
  3. @available(iOS 16.0, *) struct ApplyOverridePresetIntent: AppIntent {
  4. // Title of the action in the Shortcuts app
  5. static var title = LocalizedStringResource("Activate an override", table: "ShortcutsDetail")
  6. // Description of the action in the Shortcuts app
  7. static var description = IntentDescription(.init("Activate an override", table: "ShortcutsDetail"))
  8. internal var intentRequest: OverridePresetsIntentRequest
  9. init() {
  10. intentRequest = OverridePresetsIntentRequest()
  11. }
  12. @Parameter(
  13. title: LocalizedStringResource("Override", table: "ShortcutsDetail"),
  14. description: LocalizedStringResource("Override choice", table: "ShortcutsDetail")
  15. ) var preset: OverridePreset?
  16. @Parameter(
  17. title: LocalizedStringResource("Confirm Before applying", table: "ShortcutsDetail"),
  18. description: LocalizedStringResource("If toggled, you will need to confirm before applying", table: "ShortcutsDetail"),
  19. default: true
  20. ) var confirmBeforeApplying: Bool
  21. static var parameterSummary: some ParameterSummary {
  22. When(\ApplyOverridePresetIntent.$confirmBeforeApplying, .equalTo, true, {
  23. Summary("Applying \(\.$preset) override", table: "ShortcutsDetail") {
  24. \.$confirmBeforeApplying
  25. }
  26. }, otherwise: {
  27. Summary("Immediately applying \(\.$preset) override", table: "ShortcutsDetail") {
  28. \.$confirmBeforeApplying
  29. }
  30. })
  31. }
  32. @MainActor func perform() async throws -> some ProvidesDialog {
  33. do {
  34. let presetToApply: OverridePreset
  35. if let preset = preset {
  36. presetToApply = preset
  37. } else {
  38. presetToApply = try await $preset.requestDisambiguation(
  39. among: await intentRequest.fetchAndProcessOverrides(),
  40. dialog: IntentDialog(LocalizedStringResource("Select override", table: "ShortcutsDetail"))
  41. )
  42. }
  43. let displayName: String = presetToApply.name
  44. if confirmBeforeApplying {
  45. try await requestConfirmation(
  46. result: .result(
  47. dialog: IntentDialog(LocalizedStringResource(
  48. "Confirm to apply override '\(displayName)'",
  49. table: "ShortcutsDetail"
  50. ))
  51. )
  52. )
  53. }
  54. if await intentRequest.enactOverride(presetToApply) {
  55. return .result(
  56. dialog: IntentDialog(
  57. LocalizedStringResource(
  58. "Override '\(presetToApply.name)' applied",
  59. table: "ShortcutsDetail"
  60. )
  61. )
  62. )
  63. } else {
  64. return .result(
  65. dialog: IntentDialog(
  66. LocalizedStringResource(
  67. "Override '\(presetToApply.name)' failed",
  68. table: "ShortcutsDetail"
  69. )
  70. )
  71. )
  72. }
  73. } catch {
  74. throw error
  75. }
  76. }
  77. }