@independo/capacitor-emoji-picker 1.0.0-dev.1

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.
Files changed (64) hide show
  1. package/IndependoCapacitorEmojiPicker.podspec +17 -0
  2. package/LICENSE +21 -0
  3. package/Package.swift +28 -0
  4. package/README.md +223 -0
  5. package/android/build.gradle +109 -0
  6. package/android/src/main/AndroidManifest.xml +2 -0
  7. package/android/src/main/java/app/independo/capacitoremojipicker/EmojiPicker.java +82 -0
  8. package/android/src/main/java/app/independo/capacitoremojipicker/EmojiPickerWebBridgeInterface.java +28 -0
  9. package/android/src/main/java/app/independo/capacitoremojipicker/core/EmojiCloseButtonOptions.java +18 -0
  10. package/android/src/main/java/app/independo/capacitoremojipicker/core/EmojiPickerCallback.java +11 -0
  11. package/android/src/main/java/app/independo/capacitoremojipicker/core/EmojiPickerResult.java +16 -0
  12. package/android/src/main/java/app/independo/capacitoremojipicker/core/ErrorCodes.java +14 -0
  13. package/android/src/main/java/app/independo/capacitoremojipicker/presenter/DefaultEmojiPickerDialogFactory.java +35 -0
  14. package/android/src/main/java/app/independo/capacitoremojipicker/presenter/DispatchingEmojiPickerPresenter.java +26 -0
  15. package/android/src/main/java/app/independo/capacitoremojipicker/presenter/EmojiPickerDialogFactory.java +26 -0
  16. package/android/src/main/java/app/independo/capacitoremojipicker/presenter/EmojiPickerPresenter.java +16 -0
  17. package/android/src/main/java/app/independo/capacitoremojipicker/presenter/NativeEmojiPickerPresenter.java +220 -0
  18. package/android/src/main/java/app/independo/capacitoremojipicker/presenter/WebFallbackEmojiPickerPresenter.java +228 -0
  19. package/android/src/main/java/app/independo/capacitoremojipicker/service/EmojiPickerService.java +46 -0
  20. package/android/src/main/res/.gitkeep +0 -0
  21. package/dist/docs.json +169 -0
  22. package/dist/esm/core/error-codes.d.ts +9 -0
  23. package/dist/esm/core/error-codes.js +10 -0
  24. package/dist/esm/core/error-codes.js.map +1 -0
  25. package/dist/esm/definitions.d.ts +81 -0
  26. package/dist/esm/definitions.js +2 -0
  27. package/dist/esm/definitions.js.map +1 -0
  28. package/dist/esm/index.d.ts +4 -0
  29. package/dist/esm/index.js +9 -0
  30. package/dist/esm/index.js.map +1 -0
  31. package/dist/esm/platform/web/EmojiPickerWebAdapter.d.ts +10 -0
  32. package/dist/esm/platform/web/EmojiPickerWebAdapter.js +12 -0
  33. package/dist/esm/platform/web/EmojiPickerWebAdapter.js.map +1 -0
  34. package/dist/esm/platform/web/WebEmojiPickerPresenter.d.ts +22 -0
  35. package/dist/esm/platform/web/WebEmojiPickerPresenter.js +292 -0
  36. package/dist/esm/platform/web/WebEmojiPickerPresenter.js.map +1 -0
  37. package/dist/esm/platform/web/emoji-data-source.d.ts +5 -0
  38. package/dist/esm/platform/web/emoji-data-source.js +16 -0
  39. package/dist/esm/platform/web/emoji-data-source.js.map +1 -0
  40. package/dist/esm/platform/web/nativeWebBridge.d.ts +29 -0
  41. package/dist/esm/platform/web/nativeWebBridge.js +58 -0
  42. package/dist/esm/platform/web/nativeWebBridge.js.map +1 -0
  43. package/dist/esm/service/EmojiPickerService.d.ts +16 -0
  44. package/dist/esm/service/EmojiPickerService.js +23 -0
  45. package/dist/esm/service/EmojiPickerService.js.map +1 -0
  46. package/dist/esm/web.d.ts +9 -0
  47. package/dist/esm/web.js +16 -0
  48. package/dist/esm/web.js.map +1 -0
  49. package/dist/plugin.cjs.js +3274 -0
  50. package/dist/plugin.cjs.js.map +1 -0
  51. package/dist/plugin.js +3277 -0
  52. package/dist/plugin.js.map +1 -0
  53. package/ios/Sources/EmojiPicker/Bridge/EmojiPicker.swift +79 -0
  54. package/ios/Sources/EmojiPicker/Bridge/EmojiPickerScriptMessageHandler.swift +19 -0
  55. package/ios/Sources/EmojiPicker/Core/EmojiPickerResult.swift +12 -0
  56. package/ios/Sources/EmojiPicker/Core/ErrorCodes.swift +12 -0
  57. package/ios/Sources/EmojiPicker/Presenter/DefaultEmojiKeyboardPresentationFactory.swift +370 -0
  58. package/ios/Sources/EmojiPicker/Presenter/DispatchingEmojiPickerPresenter.swift +19 -0
  59. package/ios/Sources/EmojiPicker/Presenter/EmojiKeyboardPresentationFactory.swift +36 -0
  60. package/ios/Sources/EmojiPicker/Presenter/EmojiPickerPresenter.swift +31 -0
  61. package/ios/Sources/EmojiPicker/Presenter/NativeEmojiPickerPresenter.swift +186 -0
  62. package/ios/Sources/EmojiPicker/Presenter/WebFallbackEmojiPickerPresenter.swift +122 -0
  63. package/ios/Sources/EmojiPicker/Service/EmojiPickerService.swift +25 -0
  64. package/package.json +120 -0
@@ -0,0 +1,79 @@
1
+ import Foundation
2
+ import Capacitor
3
+ import WebKit
4
+
5
+ /// Capacitor bridge for the EmojiPicker plugin.
6
+ @objc(EmojiPicker)
7
+ public class EmojiPicker: CAPPlugin, CAPBridgedPlugin {
8
+ /// Plugin identifier used by Capacitor.
9
+ public let identifier = "EmojiPicker"
10
+ /// JavaScript name used for the plugin proxy.
11
+ public let jsName = "EmojiPicker"
12
+ /// Supported plugin methods exposed to the JS layer.
13
+ public let pluginMethods: [CAPPluginMethod] = [
14
+ CAPPluginMethod(name: "present", returnType: CAPPluginReturnPromise)
15
+ ]
16
+
17
+ /// Service layer that owns presentation flow and concurrency guarding.
18
+ private var service: EmojiPickerService?
19
+ /// Retained so it isn't deallocated out from under the `WKUserContentController`.
20
+ private var scriptMessageHandler: EmojiPickerScriptMessageHandler?
21
+
22
+ private static let validCloseButtonSizes: Set<String> = ["xSmall", "small", "medium", "large"]
23
+ private static let validCloseButtonPositions: Set<String> = ["left", "center", "right"]
24
+
25
+ /// Initializes dependencies after the plugin loads.
26
+ public override func load() {
27
+ super.load()
28
+ let nativePresenter = NativeEmojiPickerPresenter(
29
+ hostViewControllerProvider: { [weak self] in self?.bridge?.viewController },
30
+ factory: DefaultEmojiKeyboardPresentationFactory()
31
+ )
32
+ let webFallbackPresenter = WebFallbackEmojiPickerPresenter(jsEvaluator: { [weak self] js, completion in
33
+ self?.bridge?.webView?.evaluateJavaScript(js) { _, _ in completion() }
34
+ })
35
+ let handler = EmojiPickerScriptMessageHandler(presenter: webFallbackPresenter)
36
+ scriptMessageHandler = handler
37
+ // Safe no-op if none was registered yet; guards against an ObjC exception ("handler with
38
+ // name already exists") if load() ever ran more than once per plugin instance.
39
+ bridge?.webView?.configuration.userContentController.removeScriptMessageHandler(forName: "capacitorEmojiPickerBridge")
40
+ bridge?.webView?.configuration.userContentController.add(handler, name: "capacitorEmojiPickerBridge")
41
+
42
+ service = EmojiPickerService(
43
+ presenter: DispatchingEmojiPickerPresenter(nativePresenter: nativePresenter, webFallbackPresenter: webFallbackPresenter)
44
+ )
45
+ }
46
+
47
+ func configureForTesting(service: EmojiPickerService?) {
48
+ self.service = service
49
+ }
50
+
51
+ /// Presents the emoji picker.
52
+ @objc func present(_ call: CAPPluginCall) {
53
+ guard let service = service else {
54
+ call.reject(ErrorCodes.notImplemented, ErrorCodes.notImplemented)
55
+ return
56
+ }
57
+
58
+ let closeButtonObject = call.getObject("closeButton")
59
+ let size = closeButtonObject?["size"] as? String ?? "medium"
60
+ let position = closeButtonObject?["position"] as? String ?? "right"
61
+ let options = EmojiPickerPresentOptions(
62
+ presentation: call.getString("presentation") ?? "auto",
63
+ closeButton: EmojiCloseButtonOptions(
64
+ size: Self.validCloseButtonSizes.contains(size) ? size : "medium",
65
+ position: Self.validCloseButtonPositions.contains(position) ? position : "right",
66
+ hidden: closeButtonObject?["hidden"] as? Bool ?? false
67
+ ),
68
+ dismissOnBackdropTap: call.getBool("dismissOnBackdropTap") ?? true
69
+ )
70
+ service.present(options: options) { result in
71
+ switch result {
72
+ case .success(let pickerResult):
73
+ call.resolve(["emoji": pickerResult.emoji as Any])
74
+ case .failure(let error):
75
+ call.reject(error.code, error.code)
76
+ }
77
+ }
78
+ }
79
+ }
@@ -0,0 +1,19 @@
1
+ import WebKit
2
+
3
+ /// Registered on the Capacitor webview's `WKUserContentController`
4
+ /// (`userContentController.add(self, name: "capacitorEmojiPickerBridge")`) so the web bottom
5
+ /// sheet can report its outcome back to a `WebFallbackEmojiPickerPresenter` once it settles.
6
+ final class EmojiPickerScriptMessageHandler: NSObject, WKScriptMessageHandler {
7
+ private let presenter: WebFallbackEmojiPickerPresenter
8
+
9
+ init(presenter: WebFallbackEmojiPickerPresenter) {
10
+ self.presenter = presenter
11
+ }
12
+
13
+ func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
14
+ guard let body = message.body as? [String: Any], let requestId = body["requestId"] as? String else {
15
+ return
16
+ }
17
+ presenter.handleBridgeMessage(requestId: requestId, emoji: body["emoji"] as? String, errorCode: body["error"] as? String)
18
+ }
19
+ }
@@ -0,0 +1,12 @@
1
+ import Foundation
2
+
3
+ /// Result of presenting the emoji picker.
4
+ struct EmojiPickerResult {
5
+ /// The selected emoji, or `nil` when the picker was dismissed without a selection.
6
+ let emoji: String?
7
+ }
8
+
9
+ /// A canonical error surfaced by the service/presenter layers.
10
+ struct EmojiPickerError: Error {
11
+ let code: String
12
+ }
@@ -0,0 +1,12 @@
1
+ import Foundation
2
+
3
+ /// Canonical error codes surfaced by the EmojiPicker plugin.
4
+ enum ErrorCodes {
5
+ /// A `present()` call was made while a picker was already active.
6
+ static let alreadyPresenting = "ALREADY_PRESENTING"
7
+ /// The requested presentation is not implemented on this platform yet.
8
+ static let notImplemented = "NOT_IMPLEMENTED"
9
+ /// The native picker UI could not be presented (e.g. no active view controller, emoji input
10
+ /// mode unavailable); distinct from user cancellation.
11
+ static let nativeUnavailable = "NATIVE_UNAVAILABLE"
12
+ }
@@ -0,0 +1,370 @@
1
+ import UIKit
2
+
3
+ /// A `UITextField` dedicated to emoji selection. Overrides `textInputMode` to force the system's
4
+ /// "emoji" keyboard input mode when available.
5
+ ///
6
+ /// UNDOCUMENTED BEHAVIOR: `UIResponder.textInputMode` is a computed property Apple documents as
7
+ /// read-only ("the text input mode currently in use"), but overriding it to return a specific
8
+ /// `UITextInputMode` is a long-standing (iOS 8+) community technique to steer which keyboard
9
+ /// variant becomes active on `becomeFirstResponder()`. Apple does not document or guarantee this
10
+ /// keeps working. If a future iOS version stops honoring it, the verification performed by
11
+ /// `EmojiKeyboardContainerViewController` after `becomeFirstResponder()` will detect that the
12
+ /// active mode's `primaryLanguage` isn't `"emoji"` and the presenter settles `NATIVE_UNAVAILABLE`
13
+ /// instead of silently showing the wrong keyboard.
14
+ final class EmojiTextField: UITextField {
15
+ override var textInputMode: UITextInputMode? {
16
+ UITextInputMode.activeInputModes.first { $0.primaryLanguage == "emoji" } ?? super.textInputMode
17
+ }
18
+ }
19
+
20
+ /// Real UIKit implementation of `EmojiKeyboardPresentationFactory`. Presents a small, transparent
21
+ /// view controller hosting an `EmojiTextField` whose only purpose is to surface the system emoji
22
+ /// keyboard and capture what the user types into it.
23
+ final class DefaultEmojiKeyboardPresentationFactory: EmojiKeyboardPresentationFactory {
24
+ func create(
25
+ hostViewController: UIViewController,
26
+ closeButtonOptions: EmojiCloseButtonOptions,
27
+ dismissOnBackdropTap: Bool,
28
+ listener: EmojiKeyboardPresentationListener
29
+ ) -> EmojiKeyboardPresentationHandle {
30
+ guard hostViewController.presentedViewController == nil else {
31
+ // Presenting on top of an already-presented view controller would be silently
32
+ // ignored/log-warned by UIKit; report unavailable instead of attempting it.
33
+ listener.onUnavailable()
34
+ return NoopHandle()
35
+ }
36
+
37
+ let container = EmojiKeyboardContainerViewController(
38
+ listener: listener,
39
+ closeButtonOptions: closeButtonOptions,
40
+ dismissOnBackdropTap: dismissOnBackdropTap
41
+ )
42
+ container.modalPresentationStyle = .overFullScreen
43
+ container.modalTransitionStyle = .crossDissolve
44
+ // Must happen AFTER modalPresentationStyle is set: reading `presentationController`
45
+ // lazily creates and caches one matching whatever style was active at that moment. Doing
46
+ // this in the view controller's own init (before this call sets .overFullScreen) caches a
47
+ // default .pageSheet-style presentation controller - with its own opaque backdrop - that
48
+ // the later style change does not replace, which was the actual cause of the white sheet
49
+ // covering the screen regardless of what modalPresentationStyle/backgroundColor said.
50
+ container.presentationController?.delegate = container
51
+ hostViewController.present(container, animated: false)
52
+
53
+ return ContainerHandle(container: container)
54
+ }
55
+
56
+ private struct NoopHandle: EmojiKeyboardPresentationHandle {
57
+ func dismiss() {}
58
+ }
59
+
60
+ private final class ContainerHandle: EmojiKeyboardPresentationHandle {
61
+ private weak var container: EmojiKeyboardContainerViewController?
62
+
63
+ init(container: EmojiKeyboardContainerViewController) {
64
+ self.container = container
65
+ }
66
+
67
+ func dismiss() {
68
+ guard let container = container, container.presentingViewController != nil else { return }
69
+ container.dismiss(animated: false)
70
+ }
71
+ }
72
+ }
73
+
74
+ /// Where the close button docks above the keyboard.
75
+ enum EmojiCloseButtonPosition: String {
76
+ case left
77
+ case center
78
+ case right
79
+ }
80
+
81
+ /// The close button's size. Raw values match the wire format from `EmojiCloseButtonOptions.size`.
82
+ enum EmojiCloseButtonSize: String {
83
+ case xSmall
84
+ case small
85
+ case medium
86
+ case large
87
+
88
+ var pointSize: CGFloat {
89
+ switch self {
90
+ case .xSmall: return 24
91
+ case .small: return 32
92
+ case .medium: return 48
93
+ case .large: return 64
94
+ }
95
+ }
96
+
97
+ /// Keeps the glyph proportional to the button - matches the 64pt/24pt ratio the button
98
+ /// shipped with before sizing became configurable.
99
+ var symbolPointSize: CGFloat {
100
+ pointSize * 0.375
101
+ }
102
+ }
103
+
104
+ /// Hosts the invisible `EmojiTextField`, verifies the emoji input mode actually activated, and
105
+ /// forwards selection/dismissal/failure to its `listener` at most once.
106
+ ///
107
+ /// Internal (not `private`) so `EmojiTextFieldDelegateTests` can exercise
108
+ /// `textField(_:shouldChangeCharactersIn:replacementString:)` directly via `@testable import` -
109
+ /// real emoji-keyboard presentation is not driveable headlessly in XCTest, but the full-string
110
+ /// capture contract at this layer is.
111
+ final class EmojiKeyboardContainerViewController: UIViewController, UITextFieldDelegate, UIAdaptivePresentationControllerDelegate, UIGestureRecognizerDelegate {
112
+
113
+ /// How long to wait for `UITextInputCurrentInputModeDidChangeNotification` to confirm the
114
+ /// emoji mode before giving up. Tunable after manual device QA.
115
+ private static let emojiModeVerificationTimeout: TimeInterval = 0.5
116
+
117
+ /// Vertical gap between the close button and the top edge of the keyboard.
118
+ private static let closeButtonKeyboardGap: CGFloat = 12
119
+ private static let closeButtonEdgeInset: CGFloat = 16
120
+
121
+ private weak var listener: EmojiKeyboardPresentationListener?
122
+ private let closeButtonOptions: EmojiCloseButtonOptions
123
+ /// `dismissOnBackdropTap` OR'd with `closeButtonOptions.hidden`: a hidden close button must
124
+ /// never leave the user with zero ways to dismiss the keyboard, so hiding it force-enables
125
+ /// backdrop-tap-to-dismiss regardless of what was explicitly requested.
126
+ private let effectiveDismissOnBackdropTap: Bool
127
+ private let emojiField = EmojiTextField()
128
+ private let closeButton: UIButton
129
+ private var modeChangeObserver: NSObjectProtocol?
130
+ private var verificationTimeoutWorkItem: DispatchWorkItem?
131
+ private var hasReportedOutcome = false
132
+
133
+ init(listener: EmojiKeyboardPresentationListener, closeButtonOptions: EmojiCloseButtonOptions, dismissOnBackdropTap: Bool) {
134
+ self.listener = listener
135
+ self.closeButtonOptions = closeButtonOptions
136
+ self.effectiveDismissOnBackdropTap = dismissOnBackdropTap || closeButtonOptions.hidden
137
+ self.closeButton = Self.makeCloseButton(options: closeButtonOptions)
138
+ super.init(nibName: nil, bundle: nil)
139
+ }
140
+
141
+ @available(*, unavailable)
142
+ required init?(coder: NSCoder) {
143
+ fatalError("init(coder:) has not been implemented")
144
+ }
145
+
146
+ override func viewDidLoad() {
147
+ super.viewDidLoad()
148
+ view.backgroundColor = .clear
149
+
150
+ emojiField.delegate = self
151
+ emojiField.alpha = 0
152
+ emojiField.frame = CGRect(x: 0, y: 0, width: 1, height: 1)
153
+ view.addSubview(emojiField)
154
+
155
+ setUpCloseButton()
156
+ setUpBackdropTapIfNeeded()
157
+ }
158
+
159
+ override func viewDidAppear(_ animated: Bool) {
160
+ super.viewDidAppear(animated)
161
+
162
+ guard emojiField.becomeFirstResponder() else {
163
+ reportUnavailable()
164
+ return
165
+ }
166
+
167
+ if emojiField.textInputMode?.primaryLanguage == "emoji" {
168
+ return
169
+ }
170
+
171
+ modeChangeObserver = NotificationCenter.default.addObserver(
172
+ forName: UITextInputMode.currentInputModeDidChangeNotification,
173
+ object: nil,
174
+ queue: .main
175
+ ) { [weak self] _ in
176
+ self?.handleInputModeChange()
177
+ }
178
+
179
+ let timeoutWorkItem = DispatchWorkItem { [weak self] in
180
+ self?.handleVerificationTimeout()
181
+ }
182
+ verificationTimeoutWorkItem = timeoutWorkItem
183
+ DispatchQueue.main.asyncAfter(deadline: .now() + Self.emojiModeVerificationTimeout, execute: timeoutWorkItem)
184
+ }
185
+
186
+ private func handleInputModeChange() {
187
+ guard emojiField.textInputMode?.primaryLanguage == "emoji" else { return }
188
+ verificationTimeoutWorkItem?.cancel()
189
+ clearModeChangeObserver()
190
+ }
191
+
192
+ private func handleVerificationTimeout() {
193
+ guard emojiField.textInputMode?.primaryLanguage != "emoji" else {
194
+ clearModeChangeObserver()
195
+ return
196
+ }
197
+ clearModeChangeObserver()
198
+ reportUnavailable()
199
+ }
200
+
201
+ private func clearModeChangeObserver() {
202
+ if let observer = modeChangeObserver {
203
+ NotificationCenter.default.removeObserver(observer)
204
+ modeChangeObserver = nil
205
+ }
206
+ verificationTimeoutWorkItem = nil
207
+ }
208
+
209
+ /// A close button styled to match the system's own controls (Liquid Glass capsule on iOS 26+,
210
+ /// a plain circular glyph button on earlier versions), pinned to `keyboardLayoutGuide` so it
211
+ /// tracks the keyboard's position/animation directly, with a gap above it - rather than an
212
+ /// `inputAccessoryView`, which iOS renders with its own system background material docked
213
+ /// flush to the keyboard.
214
+ private static func makeCloseButton(options: EmojiCloseButtonOptions) -> UIButton {
215
+ let size = EmojiCloseButtonSize(rawValue: options.size) ?? .medium
216
+ let symbolConfiguration = UIImage.SymbolConfiguration(pointSize: size.symbolPointSize, weight: .medium)
217
+
218
+ // `UIButton.Configuration.glass()` is iOS 26 SDK API, only present when compiling with the
219
+ // Swift 6.2 toolchain Xcode 26 ships. `#available` alone isn't enough to gate this: it's a
220
+ // runtime check, but the `.glass` symbol must also resolve at compile time, which fails on
221
+ // older Xcode/SDKs regardless of the runtime guard. Gate the whole branch behind a compiler
222
+ // version check so older toolchains never see this code.
223
+ #if compiler(>=6.2)
224
+ if #available(iOS 26.0, *) {
225
+ var configuration = UIButton.Configuration.glass()
226
+ configuration.image = UIImage(systemName: "xmark")
227
+ configuration.preferredSymbolConfigurationForImage = symbolConfiguration
228
+ configuration.cornerStyle = .capsule
229
+ return UIButton(configuration: configuration)
230
+ }
231
+ #endif
232
+
233
+ let button = UIButton(type: .system)
234
+ button.setImage(UIImage(systemName: "xmark.circle.fill", withConfiguration: symbolConfiguration), for: .normal)
235
+ button.tintColor = .label
236
+ return button
237
+ }
238
+
239
+ private func setUpCloseButton() {
240
+ guard !closeButtonOptions.hidden else { return }
241
+
242
+ let size = EmojiCloseButtonSize(rawValue: closeButtonOptions.size) ?? .medium
243
+ closeButton.addTarget(self, action: #selector(closeTapped), for: .touchUpInside)
244
+ closeButton.translatesAutoresizingMaskIntoConstraints = false
245
+ view.addSubview(closeButton)
246
+
247
+ NSLayoutConstraint.activate([
248
+ closeButton.bottomAnchor.constraint(
249
+ equalTo: view.keyboardLayoutGuide.topAnchor,
250
+ constant: -Self.closeButtonKeyboardGap
251
+ ),
252
+ closeButton.widthAnchor.constraint(equalToConstant: size.pointSize),
253
+ closeButton.heightAnchor.constraint(equalToConstant: size.pointSize),
254
+ ])
255
+ let position = EmojiCloseButtonPosition(rawValue: closeButtonOptions.position) ?? .right
256
+ switch position {
257
+ case .left:
258
+ closeButton.leadingAnchor.constraint(
259
+ equalTo: view.safeAreaLayoutGuide.leadingAnchor,
260
+ constant: Self.closeButtonEdgeInset
261
+ ).isActive = true
262
+ case .center:
263
+ closeButton.centerXAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerXAnchor).isActive = true
264
+ case .right:
265
+ closeButton.trailingAnchor.constraint(
266
+ equalTo: view.safeAreaLayoutGuide.trailingAnchor,
267
+ constant: -Self.closeButtonEdgeInset
268
+ ).isActive = true
269
+ }
270
+ }
271
+
272
+ /// Adds a tap gesture that dismisses when the user taps the transparent backdrop - anywhere
273
+ /// in `view` that isn't a subview (the close button, primarily). The system keyboard itself
274
+ /// lives in a separate window/responder chain, so this can't intercept its touches.
275
+ private func setUpBackdropTapIfNeeded() {
276
+ guard effectiveDismissOnBackdropTap else { return }
277
+ let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleBackdropTap))
278
+ tapRecognizer.delegate = self
279
+ view.addGestureRecognizer(tapRecognizer)
280
+ }
281
+
282
+ // MARK: UIGestureRecognizerDelegate
283
+
284
+ func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
285
+ // Only recognize taps landing directly on the backdrop view itself, not on subviews
286
+ // (the close button handles its own taps via its target/action).
287
+ touch.view === view
288
+ }
289
+
290
+ @objc private func closeTapped() {
291
+ reportDismissed()
292
+ }
293
+
294
+ @objc func handleBackdropTap() {
295
+ reportDismissed()
296
+ }
297
+
298
+ // MARK: UITextFieldDelegate
299
+
300
+ func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
301
+ // The system lets the user switch away from the emoji keyboard (e.g. the "ABC" key) even
302
+ // though it was forced active on becomeFirstResponder(). Rather than trying to block that
303
+ // switch (there's no documented API to do so), filter here: only a single emoji Character
304
+ // is ever forwarded as a selection, so plain text typed after switching keyboards is
305
+ // silently ignored instead of being reported as if it were a picked emoji.
306
+ guard let character = string.first, string.count == 1, character.isEmoji else { return false }
307
+ reportSelected(string)
308
+ return false
309
+ }
310
+
311
+ // MARK: UIAdaptivePresentationControllerDelegate
312
+
313
+ func presentationControllerDidDismiss(_ presentationController: UIPresentationController) {
314
+ // Defensive: catches dismissal not initiated by our own code paths above.
315
+ reportDismissed()
316
+ }
317
+
318
+ // MARK: Outcome reporting (exactly once)
319
+
320
+ private func reportSelected(_ emoji: String) {
321
+ guard !hasReportedOutcome else { return }
322
+ hasReportedOutcome = true
323
+ clearModeChangeObserver()
324
+ listener?.onEmojiSelected(emoji)
325
+ dismiss(animated: true)
326
+ }
327
+
328
+ private func reportDismissed() {
329
+ guard !hasReportedOutcome else { return }
330
+ hasReportedOutcome = true
331
+ clearModeChangeObserver()
332
+ listener?.onDismissed()
333
+ dismiss(animated: true)
334
+ }
335
+
336
+ private func reportUnavailable() {
337
+ guard !hasReportedOutcome else { return }
338
+ hasReportedOutcome = true
339
+ clearModeChangeObserver()
340
+ listener?.onUnavailable()
341
+ dismiss(animated: false)
342
+ }
343
+
344
+ // UIKeyboardType(rawValue: 124) is intentionally not used here. The issue frames it as an
345
+ // optional, non-guaranteed secondary mechanism; stacking it alongside the textInputMode
346
+ // override would add iOS-version-breakage surface with no corresponding test story. Revisit
347
+ // as a follow-up only if the textInputMode override proves unreliable during manual QA.
348
+ }
349
+
350
+ /// Distinguishes real emoji characters from plain text, so input captured after the user manually
351
+ /// switches away from the forced emoji keyboard (there is no documented API to prevent that
352
+ /// switch) can be filtered out instead of being reported as a picked emoji.
353
+ extension Character {
354
+ var isEmoji: Bool {
355
+ isSimpleEmoji || isCombinedIntoEmoji
356
+ }
357
+
358
+ /// A single scalar that is itself presented as an emoji (excludes plain digits/punctuation
359
+ /// that merely have the Unicode `Emoji` property for use in keycap sequences).
360
+ private var isSimpleEmoji: Bool {
361
+ guard let firstScalar = unicodeScalars.first else { return false }
362
+ return firstScalar.properties.isEmojiPresentation || firstScalar.value > 0x238C
363
+ }
364
+
365
+ /// A multi-scalar grapheme cluster (ZWJ sequence, flag, skin-tone modifier, keycap) whose
366
+ /// first scalar participates in emoji composition.
367
+ private var isCombinedIntoEmoji: Bool {
368
+ unicodeScalars.count > 1 && unicodeScalars.contains { $0.properties.isEmoji }
369
+ }
370
+ }
@@ -0,0 +1,19 @@
1
+ import Foundation
2
+
3
+ /// Picks between the native and web-fallback presenters by `options.presentation`, so
4
+ /// `EmojiPickerService`'s single concurrency guard covers both paths uniformly - from its point
5
+ /// of view this is just another `EmojiPickerPresenter`.
6
+ final class DispatchingEmojiPickerPresenter: EmojiPickerPresenter {
7
+ private let nativePresenter: EmojiPickerPresenter
8
+ private let webFallbackPresenter: EmojiPickerPresenter
9
+
10
+ init(nativePresenter: EmojiPickerPresenter, webFallbackPresenter: EmojiPickerPresenter) {
11
+ self.nativePresenter = nativePresenter
12
+ self.webFallbackPresenter = webFallbackPresenter
13
+ }
14
+
15
+ func present(options: EmojiPickerPresentOptions, completion: @escaping (Result<EmojiPickerResult, EmojiPickerError>) -> Void) {
16
+ let target = options.presentation == "web" ? webFallbackPresenter : nativePresenter
17
+ target.present(options: options, completion: completion)
18
+ }
19
+ }
@@ -0,0 +1,36 @@
1
+ import UIKit
2
+
3
+ /// Builds the native emoji-keyboard presentation UI.
4
+ ///
5
+ /// Isolates UITextField/UIViewController construction from `NativeEmojiPickerPresenter` so the
6
+ /// presenter's settle-once/re-entrancy logic can be unit-tested with a fake, without touching
7
+ /// real UIKit responder/keyboard machinery (which XCTest cannot reliably drive headlessly).
8
+ protocol EmojiKeyboardPresentationFactory {
9
+ /// Creates and presents the emoji-keyboard UI atop `hostViewController`, reporting outcomes
10
+ /// via `listener`. Must not throw; construction failures are reported via
11
+ /// `listener.onUnavailable()` instead, since on iOS whether the emoji input mode actually
12
+ /// activates can only be confirmed asynchronously after presentation begins.
13
+ func create(
14
+ hostViewController: UIViewController,
15
+ closeButtonOptions: EmojiCloseButtonOptions,
16
+ dismissOnBackdropTap: Bool,
17
+ listener: EmojiKeyboardPresentationListener
18
+ ) -> EmojiKeyboardPresentationHandle
19
+ }
20
+
21
+ /// Callback used by the factory's implementation to report selection/dismissal/failure.
22
+ protocol EmojiKeyboardPresentationListener: AnyObject {
23
+ /// A full replacement string (which may be a multi-scalar grapheme cluster: skin tone
24
+ /// modifier, ZWJ sequence, or flag) was captured from the emoji keyboard.
25
+ func onEmojiSelected(_ emoji: String)
26
+ /// The user dismissed the keyboard/chrome without selecting anything.
27
+ func onDismissed()
28
+ /// The emoji input mode could not be verified active (or another unrecoverable UIKit-level
29
+ /// failure occurred) after presentation was attempted.
30
+ func onUnavailable()
31
+ }
32
+
33
+ /// Handle allowing the presenter to dismiss a previously-shown presentation defensively.
34
+ protocol EmojiKeyboardPresentationHandle {
35
+ func dismiss()
36
+ }
@@ -0,0 +1,31 @@
1
+ import Foundation
2
+
3
+ /// Close-button configuration for a single `present()` call. Only consulted by presenters that
4
+ /// render their own close affordance (currently iOS's native presenter); ignored elsewhere.
5
+ struct EmojiCloseButtonOptions {
6
+ /// `"xSmall"`, `"small"`, `"medium"`, or `"large"`.
7
+ let size: String
8
+ /// `"left"`, `"center"`, or `"right"`.
9
+ let position: String
10
+ let hidden: Bool
11
+ }
12
+
13
+ /// Options for a single `present()` call, forwarded from the JS layer down to whichever
14
+ /// presenter/factory ends up handling it.
15
+ struct EmojiPickerPresentOptions {
16
+ /// `"auto"` or `"web"`.
17
+ let presentation: String
18
+ let closeButton: EmojiCloseButtonOptions
19
+ /// Only consulted by presenters that render a close affordance; ignored elsewhere.
20
+ let dismissOnBackdropTap: Bool
21
+ }
22
+
23
+ /// Performs the platform-specific presentation.
24
+ ///
25
+ /// Kept separate from the Capacitor bridge and service so the native/system emoji keyboard
26
+ /// presentation (issue #5) can be implemented without touching plugin wiring or the
27
+ /// concurrency-guard logic.
28
+ protocol EmojiPickerPresenter {
29
+ /// Presents the picker for the given options and reports the outcome.
30
+ func present(options: EmojiPickerPresentOptions, completion: @escaping (Result<EmojiPickerResult, EmojiPickerError>) -> Void)
31
+ }