@zapiack/react-native 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,86 @@
1
+ import Foundation
2
+
3
+ /// Where the app and its notification extension keep what they share.
4
+ public protocol KeyValueStorage: AnyObject {
5
+ func string(forKey key: String) -> String?
6
+ func set(_ value: String?, forKey key: String)
7
+ }
8
+
9
+ public final class MemoryStorage: KeyValueStorage {
10
+ private var values: [String: String] = [:]
11
+ private let lock = NSLock()
12
+
13
+ public init() {}
14
+
15
+ public func string(forKey key: String) -> String? {
16
+ lock.lock(); defer { lock.unlock() }
17
+ return values[key]
18
+ }
19
+
20
+ public func set(_ value: String?, forKey key: String) {
21
+ lock.lock(); defer { lock.unlock() }
22
+ values[key] = value
23
+ }
24
+ }
25
+
26
+ /// Backed by an App Group, which is what lets the app and its extension see the same values.
27
+ public final class SharedDefaultsStorage: KeyValueStorage {
28
+ private let defaults: UserDefaults
29
+
30
+ public init?(appGroup: String) {
31
+ guard let defaults = UserDefaults(suiteName: appGroup) else { return nil }
32
+ self.defaults = defaults
33
+ }
34
+
35
+ public func string(forKey key: String) -> String? { defaults.string(forKey: key) }
36
+
37
+ public func set(_ value: String?, forKey key: String) {
38
+ if let value { defaults.set(value, forKey: key) } else { defaults.removeObject(forKey: key) }
39
+ }
40
+ }
41
+
42
+ public struct ZapiackConfig: Equatable {
43
+ public var appKey: String
44
+ public var baseUrl: URL
45
+ public var installationId: String
46
+
47
+ public init(appKey: String, baseUrl: URL, installationId: String) {
48
+ self.appKey = appKey
49
+ self.baseUrl = baseUrl
50
+ self.installationId = installationId
51
+ }
52
+ }
53
+
54
+ /// What the app writes at start-up and the extension reads when a push arrives.
55
+ public enum SharedState {
56
+ public static let defaultBaseUrl = URL(string: "https://api.zapiack.com/v1")!
57
+
58
+ enum Key {
59
+ static let appKey = "zapiack.appKey"
60
+ static let baseUrl = "zapiack.baseUrl"
61
+ static let installationId = "zapiack.installationId"
62
+ static let session = "zapiack.session"
63
+ static let user = "zapiack.user"
64
+ static let tags = "zapiack.tags"
65
+ }
66
+
67
+ /// A UUID made on first use and kept: it identifies this install even when its push address changes.
68
+ public static func installationId(in storage: KeyValueStorage) -> String {
69
+ if let existing = storage.string(forKey: Key.installationId), !existing.isEmpty { return existing }
70
+ let created = UUID().uuidString.lowercased()
71
+ storage.set(created, forKey: Key.installationId)
72
+ return created
73
+ }
74
+
75
+ public static func save(appKey: String, baseUrl: URL, in storage: KeyValueStorage) {
76
+ storage.set(appKey, forKey: Key.appKey)
77
+ storage.set(baseUrl.absoluteString, forKey: Key.baseUrl)
78
+ }
79
+
80
+ public static func load(from storage: KeyValueStorage) -> ZapiackConfig? {
81
+ guard let appKey = storage.string(forKey: Key.appKey), appKey.hasPrefix("pk_"),
82
+ let base = storage.string(forKey: Key.baseUrl), let baseUrl = URL(string: base)
83
+ else { return nil }
84
+ return ZapiackConfig(appKey: appKey, baseUrl: baseUrl, installationId: installationId(in: storage))
85
+ }
86
+ }
@@ -0,0 +1,170 @@
1
+ #if canImport(ActivityKit) && canImport(WidgetKit) && os(iOS)
2
+ import ActivityKit
3
+ import SwiftUI
4
+ import WidgetKit
5
+
6
+ /// Draws Zapiack Live Activities. Add it to your widget extension's bundle:
7
+ ///
8
+ /// ```swift
9
+ /// @main struct Widgets: WidgetBundle {
10
+ /// var body: some Widget { ZapiackLiveActivityWidget() }
11
+ /// }
12
+ /// ```
13
+ ///
14
+ /// The countdown is the system's own timer text, so it ticks every second on the lock screen with no work from the app and no
15
+ /// further push. When the timer ends the activity goes stale, and it shows what the template asked for at the end.
16
+ @available(iOS 16.2, *)
17
+ public struct ZapiackLiveActivityWidget: Widget {
18
+ public init() {}
19
+
20
+ public var body: some WidgetConfiguration {
21
+ ActivityConfiguration(for: ZapiackLiveAttributes.self) { context in
22
+ ActivityBody(state: context.state, stale: context.isStale)
23
+ .activityBackgroundTint(context.state.background.flatMap(Color.init(hex:)))
24
+ .widgetURL(context.attributes.link.flatMap(URL.init(string:)))
25
+ } dynamicIsland: { context in
26
+ let state = context.state
27
+ let stale = context.isStale
28
+ return DynamicIsland {
29
+ DynamicIslandExpandedRegion(.leading) {
30
+ Text(state.title).font(.headline).lineLimit(1)
31
+ }
32
+ DynamicIslandExpandedRegion(.trailing) {
33
+ TimerText(state: state, stale: stale, size: 22)
34
+ }
35
+ DynamicIslandExpandedRegion(.bottom) {
36
+ VStack(alignment: .leading, spacing: 6) {
37
+ if let label = state.timerLabel, !label.isEmpty { Text(label).font(.caption).foregroundStyle(.secondary) }
38
+ ProgressSteps(state: state)
39
+ }
40
+ }
41
+ } compactLeading: {
42
+ Image(systemName: state.timerEnd != nil ? "timer" : "shippingbox")
43
+ .foregroundStyle(Color(hex: state.timerColor ?? state.progressColor ?? "") ?? .accentColor)
44
+ } compactTrailing: {
45
+ TimerText(state: state, stale: stale, size: 14)
46
+ .frame(maxWidth: 64)
47
+ } minimal: {
48
+ Image(systemName: "timer")
49
+ }
50
+ .widgetURL(context.attributes.link.flatMap(URL.init(string:)))
51
+ }
52
+ }
53
+ }
54
+
55
+ /** A grid design draws its own layout; anything else, the standard Zapiack card. */
56
+ @available(iOS 16.2, *)
57
+ struct ActivityBody: View {
58
+ let state: ZapiackLiveAttributes.ContentState
59
+ let stale: Bool
60
+
61
+ var body: some View {
62
+ if let tree = ZapiackLayoutNode.parse(state.layout) {
63
+ ZapiackLayoutView(
64
+ node: tree,
65
+ content: ZapiackLayoutContent(title: state.title, body: state.body, live: ZapiackLiveItem.parse(state.live), actions: state.actions ?? [], background: state.background, timerEnd: state.timerEnd)
66
+ )
67
+ .padding(14)
68
+ } else {
69
+ LockScreenView(state: state, stale: stale)
70
+ }
71
+ }
72
+ }
73
+
74
+ @available(iOS 16.2, *)
75
+ struct LockScreenView: View {
76
+ let state: ZapiackLiveAttributes.ContentState
77
+ let stale: Bool
78
+
79
+ var body: some View {
80
+ HStack(alignment: .center, spacing: 12) {
81
+ VStack(alignment: .leading, spacing: 6) {
82
+ if let badge = state.badgeText, !badge.isEmpty {
83
+ Text(badge)
84
+ .font(.caption2.weight(.semibold))
85
+ .padding(.horizontal, 8).padding(.vertical, 2)
86
+ .background(Capsule().fill(Color(hex: state.badgeColor ?? "") ?? .green))
87
+ .foregroundStyle(.white)
88
+ }
89
+ Text(state.title).font(.headline).lineLimit(1)
90
+ TimerText(state: state, stale: stale, size: 34)
91
+ if let label = state.timerLabel, !label.isEmpty, !(stale && state.timerOnEnd == "expired") {
92
+ Text(label).font(.footnote.weight(.medium)).foregroundStyle(Color(hex: state.timerColor ?? "") ?? .secondary).lineLimit(2)
93
+ } else if state.timerEnd == nil, let body = state.body, !body.isEmpty {
94
+ Text(body).font(.subheadline).foregroundStyle(.secondary).lineLimit(2)
95
+ }
96
+ ProgressSteps(state: state)
97
+ if let value = state.counterValue {
98
+ Text("\(value.formatted()) \(state.counterLabel ?? "")").font(.subheadline.weight(.semibold))
99
+ }
100
+ }
101
+ Spacer(minLength: 0)
102
+ }
103
+ .padding(16)
104
+ }
105
+ }
106
+
107
+ /// The countdown. Before the end it is the system timer; after, it is the template's ended state.
108
+ @available(iOS 16.2, *)
109
+ struct TimerText: View {
110
+ let state: ZapiackLiveAttributes.ContentState
111
+ let stale: Bool
112
+ let size: CGFloat
113
+
114
+ var body: some View {
115
+ if let end = state.timerEnd {
116
+ let color = Color(hex: state.timerColor ?? "") ?? .primary
117
+ let over = stale || end <= Date()
118
+ if over {
119
+ switch state.timerOnEnd {
120
+ case "hide": EmptyView()
121
+ case "expired": Text(state.expiredText ?? "").font(.system(size: size * 0.5, weight: .semibold)).foregroundStyle(color)
122
+ default: Text(state.timerFormat == "mmss" ? "00:00" : "0:00:00").font(.system(size: size, weight: .bold)).monospacedDigit().foregroundStyle(color)
123
+ }
124
+ } else if state.timerFormat == "dhm" {
125
+ // Days are too long to tick by the second: the system writes how long is left and keeps it current.
126
+ Text(end, style: .relative).font(.system(size: size * 0.7, weight: .bold)).foregroundStyle(color)
127
+ } else {
128
+ Text(timerInterval: Date()...end, countsDown: true)
129
+ .font(.system(size: size, weight: .bold))
130
+ .monospacedDigit()
131
+ .foregroundStyle(color)
132
+ .multilineTextAlignment(.leading)
133
+ }
134
+ }
135
+ }
136
+ }
137
+
138
+ @available(iOS 16.2, *)
139
+ struct ProgressSteps: View {
140
+ let state: ZapiackLiveAttributes.ContentState
141
+
142
+ var body: some View {
143
+ if let steps = state.progressSteps, steps.count >= 2 {
144
+ let done = min(max(state.progressCurrent ?? 0, 0), steps.count)
145
+ let tint = Color(hex: state.progressColor ?? "") ?? .green
146
+ VStack(alignment: .leading, spacing: 4) {
147
+ HStack(spacing: 4) {
148
+ ForEach(0..<steps.count, id: \.self) { i in
149
+ Capsule().fill(i < done ? tint : Color.secondary.opacity(0.25)).frame(height: 4)
150
+ }
151
+ }
152
+ HStack(spacing: 4) {
153
+ ForEach(0..<steps.count, id: \.self) { i in
154
+ Text(steps[i]).font(.caption2).foregroundStyle(.secondary).lineLimit(1).frame(maxWidth: .infinity, alignment: i == 0 ? .leading : i == steps.count - 1 ? .trailing : .center)
155
+ }
156
+ }
157
+ }
158
+ }
159
+ }
160
+ }
161
+
162
+ extension Color {
163
+ /// A #RRGGBB colour, or nil for anything else.
164
+ init?(hex: String) {
165
+ let s = hex.trimmingCharacters(in: .whitespaces)
166
+ guard s.count == 7, s.hasPrefix("#"), let n = UInt32(s.dropFirst(), radix: 16) else { return nil }
167
+ self.init(red: Double((n >> 16) & 0xFF) / 255, green: Double((n >> 8) & 0xFF) / 255, blue: Double(n & 0xFF) / 255)
168
+ }
169
+ }
170
+ #endif
@@ -0,0 +1,78 @@
1
+ #if canImport(ActivityKit) && os(iOS)
2
+ import ActivityKit
3
+ import Foundation
4
+
5
+ /// The Live Activity a Zapiack template push starts: a countdown, progress or counter that stays on the lock screen and in the
6
+ /// Dynamic Island and updates on its own. Zapiack fills it in from the template when it sends; the app only has to show it, by adding
7
+ /// `ZapiackLiveActivityWidget` to its widget extension.
8
+ ///
9
+ /// The field names match what the Zapiack service sends (`liveContentState` on the server). Dates are plain numbers, seconds since
10
+ /// 1970, so they decode the same way whatever the decoder's date setting is.
11
+ @available(iOS 16.1, *)
12
+ public struct ZapiackLiveAttributes: ActivityAttributes {
13
+ public struct ContentState: Codable, Hashable {
14
+ public var title: String
15
+ public var body: String?
16
+ /// The template's background, as #RRGGBB. Absent means the system's own lock screen look.
17
+ public var background: String?
18
+
19
+ public var timerEndsAt: Double?
20
+ /// hmmss, mmss or dhm.
21
+ public var timerFormat: String?
22
+ public var timerColor: String?
23
+ public var timerLabel: String?
24
+ /// What happens when the timer ends: expired (show `expiredText`), hide (no timer) or keep (zeroes).
25
+ public var timerOnEnd: String?
26
+ public var expiredText: String?
27
+
28
+ public var progressSteps: [String]?
29
+ public var progressCurrent: Int?
30
+ public var progressColor: String?
31
+
32
+ public var counterValue: Double?
33
+ public var counterLabel: String?
34
+
35
+ public var badgeText: String?
36
+ public var badgeColor: String?
37
+
38
+ /// A grid design: the layout tree, its live elements and its button labels, so the activity draws the same layout.
39
+ public var layout: String?
40
+ public var live: String?
41
+ public var actions: [String]?
42
+
43
+ public init(title: String, body: String? = nil, background: String? = nil, timerEndsAt: Double? = nil, timerFormat: String? = nil, timerColor: String? = nil, timerLabel: String? = nil, timerOnEnd: String? = nil, expiredText: String? = nil, progressSteps: [String]? = nil, progressCurrent: Int? = nil, progressColor: String? = nil, counterValue: Double? = nil, counterLabel: String? = nil, badgeText: String? = nil, badgeColor: String? = nil) {
44
+ self.title = title
45
+ self.body = body
46
+ self.background = background
47
+ self.timerEndsAt = timerEndsAt
48
+ self.timerFormat = timerFormat
49
+ self.timerColor = timerColor
50
+ self.timerLabel = timerLabel
51
+ self.timerOnEnd = timerOnEnd
52
+ self.expiredText = expiredText
53
+ self.progressSteps = progressSteps
54
+ self.progressCurrent = progressCurrent
55
+ self.progressColor = progressColor
56
+ self.counterValue = counterValue
57
+ self.counterLabel = counterLabel
58
+ self.badgeText = badgeText
59
+ self.badgeColor = badgeColor
60
+ }
61
+
62
+ /// When the timer ends, if there is one.
63
+ public var timerEnd: Date? { timerEndsAt.map { Date(timeIntervalSince1970: $0) } }
64
+ }
65
+
66
+ /// The Zapiack message and delivery this activity came from, so a tap can be reported.
67
+ public var messageId: String
68
+ public var deliveryId: String
69
+ /// Where a tap takes the person: the template's link, already chosen for iOS.
70
+ public var link: String?
71
+
72
+ public init(messageId: String, deliveryId: String, link: String? = nil) {
73
+ self.messageId = messageId
74
+ self.deliveryId = deliveryId
75
+ self.link = link
76
+ }
77
+ }
78
+ #endif
@@ -0,0 +1,146 @@
1
+ import Foundation
2
+ import UserNotifications
3
+ #if canImport(ActivityKit) && os(iOS)
4
+ import ActivityKit
5
+ #endif
6
+ #if canImport(UIKit)
7
+ import UIKit
8
+ #endif
9
+
10
+
11
+ /// Push notifications for an app: ask permission, register this install, and follow what happens after a tap.
12
+ public final class ZapiackPush {
13
+ public static let shared = ZapiackPush()
14
+
15
+ private var client: PushClient?
16
+ private var appVersion: String?
17
+
18
+ private init() {}
19
+
20
+ /// Call once at launch, before anything else. `appGroup` is the App Group shared with the notification extension.
21
+ public func configure(appKey: String, appGroup: String, baseUrl: URL = SharedState.defaultBaseUrl) {
22
+ guard appKey.hasPrefix("pk_"), let storage = SharedDefaultsStorage(appGroup: appGroup),
23
+ let container = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: appGroup) else {
24
+ assertionFailure("ZapiackPush: the app key must start with pk_ and the App Group must be enabled for this target")
25
+ return
26
+ }
27
+ SharedState.save(appKey: appKey, baseUrl: baseUrl, in: storage)
28
+ guard let config = SharedState.load(from: storage) else { return }
29
+ client = PushClient(config: config, storage: storage, queue: EventQueue(directory: container.appendingPathComponent("zapiack-events", isDirectory: true)))
30
+ appVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String
31
+ Task { await self.syncRegistration() }
32
+ Task { await self.client?.flush() }
33
+ }
34
+
35
+ /// The identifier that ties this install to the service.
36
+ public var installationId: String? { client?.config.installationId }
37
+
38
+ /// Shows the system permission prompt, then registers for push when it is allowed.
39
+ @discardableResult
40
+ public func requestPermission(options: UNAuthorizationOptions = [.alert, .badge, .sound]) async -> Bool {
41
+ let granted = (try? await UNUserNotificationCenter.current().requestAuthorization(options: options)) ?? false
42
+ if granted { await registerForRemoteNotifications() }
43
+ await syncRegistration()
44
+ return granted
45
+ }
46
+
47
+ /// Hand over the token from `application(_:didRegisterForRemoteNotificationsWithDeviceToken:)`.
48
+ public func didRegisterForRemoteNotifications(deviceToken: Data) {
49
+ client?.setDeviceToken(deviceToken)
50
+ Task { await self.syncRegistration() }
51
+ }
52
+
53
+ public func login(_ userId: String) {
54
+ client?.login(userId)
55
+ Task { await self.syncRegistration() }
56
+ }
57
+
58
+ public func logout() {
59
+ client?.logout()
60
+ Task { await self.syncRegistration() }
61
+ }
62
+
63
+ public func addTags(_ tags: [String: JSONValue]) {
64
+ client?.addTags(tags)
65
+ Task { await self.syncRegistration() }
66
+ }
67
+
68
+ public func removeTags(_ keys: [String]) {
69
+ client?.removeTags(keys)
70
+ Task { await self.syncRegistration() }
71
+ }
72
+
73
+ /// Call from `userNotificationCenter(_:didReceive:withCompletionHandler:)`. Returns what was tapped so the app can route, or
74
+ /// nil when the notification is not from Zapiack or was only dismissed.
75
+ @discardableResult
76
+ public func handle(_ response: UNNotificationResponse) -> Tap? {
77
+ guard let client else { return nil }
78
+ let tap = client.handleResponse(userInfo: response.notification.request.content.userInfo, actionIdentifier: response.actionIdentifier)
79
+ if tap != nil { Task { await client.flush() } }
80
+ return tap
81
+ }
82
+
83
+ /// A screen the user reached, credited to the push they tapped while its window is open.
84
+ public func screen(_ name: String) { client?.screen(name) }
85
+
86
+ /// A named goal or event, credited to the push they tapped while its window is open.
87
+ /// Returns whether there was a tapped push to credit it to.
88
+ @discardableResult
89
+ public func track(_ name: String, properties: [String: JSONValue]? = nil) -> Bool {
90
+ let credited = client?.track(name, properties: properties) ?? false
91
+ Task { await self.client?.flush() }
92
+ return credited
93
+ }
94
+
95
+ /// Lets Zapiack start Live Activities on this phone: a template push with a timer or progress then appears on the lock screen
96
+ /// and in the Dynamic Island and counts down by itself. Needs iOS 17.2 or later, `NSSupportsLiveActivities` set to YES in the
97
+ /// app's Info.plist, and `ZapiackLiveActivityWidget` in a widget extension. On older iOS it does nothing, and those pushes
98
+ /// arrive as normal notifications.
99
+ public func enableLiveActivities() {
100
+ #if canImport(ActivityKit) && os(iOS)
101
+ if #available(iOS 17.2, *) {
102
+ guard ActivityAuthorizationInfo().areActivitiesEnabled else { return }
103
+ liveTokenTask?.cancel()
104
+ liveTokenTask = Task { [weak self] in
105
+ for await token in Activity<ZapiackLiveAttributes>.pushToStartTokenUpdates {
106
+ guard let self, let client = self.client else { continue }
107
+ if client.liveActivityToken != token.map({ String(format: "%02x", $0) }).joined() {
108
+ client.setLiveActivityToken(token)
109
+ await self.syncRegistration()
110
+ }
111
+ }
112
+ }
113
+ }
114
+ #endif
115
+ }
116
+
117
+ private var liveTokenTask: Task<Void, Never>?
118
+
119
+ /// Sends anything waiting. Call when the app comes to the foreground.
120
+ public func flush() async { await client?.flush() }
121
+
122
+ private func syncRegistration() async {
123
+ guard let client, client.deviceToken != nil else { return }
124
+ let settings = await UNUserNotificationCenter.current().notificationSettings()
125
+ let permission: String?
126
+ switch settings.authorizationStatus {
127
+ case .authorized, .ephemeral: permission = "granted"
128
+ case .provisional: permission = "provisional"
129
+ case .denied: permission = "denied"
130
+ default: permission = nil
131
+ }
132
+ #if DEBUG
133
+ let environment = "sandbox"
134
+ #else
135
+ let environment = "production"
136
+ #endif
137
+ try? await client.register(permission: permission, environment: environment, appVersion: appVersion)
138
+ }
139
+
140
+ @MainActor
141
+ private func registerForRemoteNotifications() {
142
+ #if canImport(UIKit) && !os(watchOS)
143
+ UIApplication.shared.registerForRemoteNotifications()
144
+ #endif
145
+ }
146
+ }
@@ -0,0 +1,19 @@
1
+ #import <React/RCTBridgeModule.h>
2
+ #import <React/RCTEventEmitter.h>
3
+
4
+ @interface RCT_EXTERN_MODULE (ZapiackPushModule, RCTEventEmitter)
5
+
6
+ RCT_EXTERN_METHOD(configure : (NSDictionary *)options resolver : (RCTPromiseResolveBlock)resolve rejecter : (RCTPromiseRejectBlock)reject)
7
+ RCT_EXTERN_METHOD(requestPermission : (RCTPromiseResolveBlock)resolve rejecter : (RCTPromiseRejectBlock)reject)
8
+ RCT_EXTERN_METHOD(installationId : (RCTPromiseResolveBlock)resolve rejecter : (RCTPromiseRejectBlock)reject)
9
+ RCT_EXTERN_METHOD(login : (NSString *)userId resolver : (RCTPromiseResolveBlock)resolve rejecter : (RCTPromiseRejectBlock)reject)
10
+ RCT_EXTERN_METHOD(logout : (RCTPromiseResolveBlock)resolve rejecter : (RCTPromiseRejectBlock)reject)
11
+ RCT_EXTERN_METHOD(addTags : (NSDictionary *)tags resolver : (RCTPromiseResolveBlock)resolve rejecter : (RCTPromiseRejectBlock)reject)
12
+ RCT_EXTERN_METHOD(removeTags : (NSArray *)keys resolver : (RCTPromiseResolveBlock)resolve rejecter : (RCTPromiseRejectBlock)reject)
13
+ RCT_EXTERN_METHOD(screen : (NSString *)name resolver : (RCTPromiseResolveBlock)resolve rejecter : (RCTPromiseRejectBlock)reject)
14
+ RCT_EXTERN_METHOD(track : (NSString *)name properties : (NSDictionary *)properties resolver : (RCTPromiseResolveBlock)resolve rejecter : (RCTPromiseRejectBlock)reject)
15
+ RCT_EXTERN_METHOD(flush : (RCTPromiseResolveBlock)resolve rejecter : (RCTPromiseRejectBlock)reject)
16
+ RCT_EXTERN_METHOD(enableLiveActivities : (RCTPromiseResolveBlock)resolve rejecter : (RCTPromiseRejectBlock)reject)
17
+ RCT_EXTERN_METHOD(initialTap : (RCTPromiseResolveBlock)resolve rejecter : (RCTPromiseRejectBlock)reject)
18
+
19
+ @end
@@ -0,0 +1,126 @@
1
+ import Foundation
2
+ import React
3
+ import UserNotifications
4
+
5
+ /// Connects the JavaScript API to the iOS library.
6
+ @objc(ZapiackPushModule)
7
+ final class ZapiackPushModule: RCTEventEmitter, UNUserNotificationCenterDelegate {
8
+ private var hasListeners = false
9
+ /// The tap that opened the app, kept until JavaScript asks for it, because it is not listening yet when the app starts.
10
+ private static var initialTap: Tap?
11
+
12
+ override init() {
13
+ super.init()
14
+ UNUserNotificationCenter.current().delegate = self
15
+ }
16
+
17
+ @objc override static func requiresMainQueueSetup() -> Bool { true }
18
+
19
+ override func supportedEvents() -> [String]! { ["zapiackTap"] }
20
+ override func startObserving() { hasListeners = true }
21
+ override func stopObserving() { hasListeners = false }
22
+
23
+ /// Call from the app delegate's `didRegisterForRemoteNotificationsWithDeviceToken`, which React Native does not forward.
24
+ @objc static func didRegisterForRemoteNotifications(deviceToken: Data) {
25
+ ZapiackPush.shared.didRegisterForRemoteNotifications(deviceToken: deviceToken)
26
+ }
27
+
28
+ @objc func configure(_ options: NSDictionary, resolver resolve: @escaping RCTPromiseResolveBlock, rejecter reject: @escaping RCTPromiseRejectBlock) {
29
+ guard let key = options["appKey"] as? String, key.hasPrefix("pk_") else { return reject("invalid_key", "The app key must start with pk_", nil) }
30
+ guard let group = options["appGroup"] as? String, !group.isEmpty else {
31
+ return reject("invalid_group", "On iOS, appGroup is required: it is how the app and its notification extension share what they need", nil)
32
+ }
33
+ let base = (options["baseUrl"] as? String).flatMap(URL.init(string:)) ?? SharedState.defaultBaseUrl
34
+ ZapiackPush.shared.configure(appKey: key, appGroup: group, baseUrl: base)
35
+ resolve(nil)
36
+ }
37
+
38
+ @objc func requestPermission(_ resolve: @escaping RCTPromiseResolveBlock, rejecter reject: @escaping RCTPromiseRejectBlock) {
39
+ Task { resolve(await ZapiackPush.shared.requestPermission()) }
40
+ }
41
+
42
+ @objc func installationId(_ resolve: RCTPromiseResolveBlock, rejecter reject: RCTPromiseRejectBlock) {
43
+ resolve(ZapiackPush.shared.installationId)
44
+ }
45
+
46
+ @objc func login(_ userId: String, resolver resolve: RCTPromiseResolveBlock, rejecter reject: RCTPromiseRejectBlock) {
47
+ ZapiackPush.shared.login(userId)
48
+ resolve(nil)
49
+ }
50
+
51
+ @objc func logout(_ resolve: RCTPromiseResolveBlock, rejecter reject: RCTPromiseRejectBlock) {
52
+ ZapiackPush.shared.logout()
53
+ resolve(nil)
54
+ }
55
+
56
+ @objc func addTags(_ tags: NSDictionary, resolver resolve: RCTPromiseResolveBlock, rejecter reject: RCTPromiseRejectBlock) {
57
+ ZapiackPush.shared.addTags(Self.values(tags))
58
+ resolve(nil)
59
+ }
60
+
61
+ @objc func removeTags(_ keys: NSArray, resolver resolve: RCTPromiseResolveBlock, rejecter reject: RCTPromiseRejectBlock) {
62
+ ZapiackPush.shared.removeTags(keys.compactMap { $0 as? String })
63
+ resolve(nil)
64
+ }
65
+
66
+ @objc func screen(_ name: String, resolver resolve: RCTPromiseResolveBlock, rejecter reject: RCTPromiseRejectBlock) {
67
+ ZapiackPush.shared.screen(name)
68
+ resolve(nil)
69
+ }
70
+
71
+ @objc func track(_ name: String, properties: NSDictionary?, resolver resolve: RCTPromiseResolveBlock, rejecter reject: RCTPromiseRejectBlock) {
72
+ resolve(ZapiackPush.shared.track(name, properties: properties.map(Self.values)))
73
+ }
74
+
75
+ @objc func enableLiveActivities(_ resolve: RCTPromiseResolveBlock, rejecter reject: RCTPromiseRejectBlock) {
76
+ ZapiackPush.shared.enableLiveActivities()
77
+ resolve(nil)
78
+ }
79
+
80
+ @objc func flush(_ resolve: @escaping RCTPromiseResolveBlock, rejecter reject: RCTPromiseRejectBlock) {
81
+ Task { await ZapiackPush.shared.flush(); resolve(nil) }
82
+ }
83
+
84
+ @objc func initialTap(_ resolve: RCTPromiseResolveBlock, rejecter reject: RCTPromiseRejectBlock) {
85
+ resolve(Self.initialTap.map(Self.map))
86
+ Self.initialTap = nil
87
+ }
88
+
89
+ // MARK: Taps and notifications in front
90
+
91
+ func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
92
+ if let tap = ZapiackPush.shared.handle(response) {
93
+ if hasListeners { sendEvent(withName: "zapiackTap", body: Self.map(tap)) } else { Self.initialTap = tap }
94
+ }
95
+ completionHandler()
96
+ }
97
+
98
+ func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
99
+ if #available(iOS 14.0, *) { completionHandler([.banner, .list, .sound, .badge]) } else { completionHandler([.alert, .sound, .badge]) }
100
+ }
101
+
102
+ // MARK: Helpers
103
+
104
+ private static func values(_ raw: NSDictionary) -> [String: JSONValue] {
105
+ (raw as? [String: Any] ?? [:]).mapValues(json)
106
+ }
107
+
108
+ private static func json(_ value: Any) -> JSONValue {
109
+ switch value {
110
+ case let v as NSNumber where CFGetTypeID(v) == CFBooleanGetTypeID(): return .bool(v.boolValue)
111
+ case let v as NSNumber: return .number(v.doubleValue)
112
+ case let v as String: return .string(v)
113
+ case let v as [Any]: return .array(v.map(json))
114
+ case let v as [String: Any]: return .object(v.mapValues(json))
115
+ default: return .null
116
+ }
117
+ }
118
+
119
+ private static func map(_ tap: Tap) -> [String: Any] {
120
+ var out: [String: Any] = ["messageId": tap.messageId, "deliveryId": tap.deliveryId, "sessionId": tap.sessionId]
121
+ if let a = tap.actionId { out["actionId"] = a }
122
+ if let e = tap.event { out["event"] = e }
123
+ if let l = tap.link { out["link"] = l.absoluteString }
124
+ return out
125
+ }
126
+ }