expo-widgets 58.0.15 → 58.0.17

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 (65) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/android/build.gradle +7 -2
  3. package/android/proguard-rules.pro +7 -0
  4. package/android/src/main/AndroidManifest.xml +6 -1
  5. package/android/src/main/java/expo/modules/widgets/ExpoWidgetEmittableTree.kt +7 -7
  6. package/android/src/main/java/expo/modules/widgets/ExpoWidgetsPeekWidget.kt +1 -1
  7. package/android/src/main/java/expo/modules/widgets/WidgetInteractionAction.kt +34 -4
  8. package/android/src/main/java/expo/modules/widgets/WidgetsEvents.kt +8 -4
  9. package/android/src/main/java/expo/modules/widgets/WidgetsModule.kt +45 -0
  10. package/android/src/main/java/expo/modules/widgets/notifications/CustomNotification.kt +28 -0
  11. package/android/src/main/java/expo/modules/widgets/notifications/CustomNotificationBuilder.kt +116 -0
  12. package/android/src/main/java/expo/modules/widgets/notifications/CustomNotificationExceptions.kt +50 -0
  13. package/android/src/main/java/expo/modules/widgets/notifications/CustomNotificationFactory.kt +36 -0
  14. package/android/src/main/java/expo/modules/widgets/notifications/CustomNotificationOptions.kt +86 -0
  15. package/android/src/main/java/expo/modules/widgets/notifications/CustomNotificationRenderer.kt +44 -0
  16. package/android/src/main/java/expo/modules/widgets/notifications/CustomNotificationState.kt +65 -0
  17. package/android/src/main/java/expo/modules/widgets/notifications/CustomNotifications.kt +107 -0
  18. package/android/src/main/java/expo/modules/widgets/notifications/ExpoWidgetsNotificationReceiver.kt +67 -0
  19. package/android/src/main/res/values/expo_widgets_notifications.xml +4 -0
  20. package/build/CustomNotifications.d.ts +128 -0
  21. package/build/CustomNotifications.js +162 -0
  22. package/build/CustomNotifications.js.map +1 -0
  23. package/build/CustomNotifications.types.d.ts +124 -0
  24. package/build/CustomNotifications.types.js +3 -0
  25. package/build/CustomNotifications.types.js.map +1 -0
  26. package/build/ExpoWidgets.d.ts +3 -0
  27. package/build/ExpoWidgets.js +26 -0
  28. package/build/ExpoWidgets.js.map +1 -1
  29. package/build/ExpoWidgets.native.d.ts +5 -0
  30. package/build/ExpoWidgets.native.js.map +1 -1
  31. package/build/Widgets.d.ts +14 -0
  32. package/build/Widgets.js +14 -0
  33. package/build/Widgets.js.map +1 -1
  34. package/build/Widgets.types.d.ts +24 -0
  35. package/build/index.d.ts +2 -0
  36. package/build/index.js +1 -0
  37. package/build/index.js.map +1 -1
  38. package/bundle/decorator.ts +13 -0
  39. package/bundle/index.ts +19 -2
  40. package/bundle/layout-registry-stub.ts +19 -0
  41. package/ios/ExpoWidgets.podspec +5 -7
  42. package/ios/Widgets/EntryView.swift +17 -1
  43. package/ios/Widgets/RedBoxView.swift +16 -0
  44. package/layout-registry.metro.config.js +9 -2
  45. package/package.json +4 -4
  46. package/plugin/build/android/withAndroidNotificationPermission.d.ts +6 -0
  47. package/plugin/build/android/withAndroidNotificationPermission.js +31 -0
  48. package/plugin/build/android/withAndroidNotificationPermission.js.map +1 -0
  49. package/plugin/build/android/withAndroidWidgets.d.ts +4 -2
  50. package/plugin/build/android/withAndroidWidgets.js +6 -1
  51. package/plugin/build/android/withAndroidWidgets.js.map +1 -1
  52. package/plugin/build/ios/withWidgetSourceFiles.js +1 -1
  53. package/plugin/build/withWidgets.js +1 -0
  54. package/plugin/build/withWidgets.js.map +1 -1
  55. package/plugin/src/android/withAndroidNotificationPermission.ts +22 -0
  56. package/plugin/src/android/withAndroidWidgets.ts +11 -1
  57. package/plugin/src/ios/withWidgetSourceFiles.ts +1 -1
  58. package/plugin/src/withWidgets.ts +2 -2
  59. package/src/CustomNotifications.ts +213 -0
  60. package/src/CustomNotifications.types.ts +138 -0
  61. package/src/ExpoWidgets.native.ts +8 -0
  62. package/src/ExpoWidgets.ts +41 -0
  63. package/src/Widgets.ts +14 -0
  64. package/src/Widgets.types.ts +24 -0
  65. package/src/index.ts +8 -0
@@ -0,0 +1,65 @@
1
+ package expo.modules.widgets.notifications
2
+
3
+ import android.app.Notification
4
+ import android.app.NotificationManager
5
+ import android.content.Context
6
+ import android.net.Uri
7
+ import android.os.Bundle
8
+ import android.service.notification.StatusBarNotification
9
+ import expo.modules.widgets.WidgetsJson
10
+
11
+ // Persisted in notification extras so handles and button presses work after a process restart.
12
+ internal data class CustomNotificationState(
13
+ val name: String,
14
+ val id: String,
15
+ val props: Map<String, Any?>?,
16
+ val options: CustomNotificationOptions
17
+ ) {
18
+ val tag: String get() = tag(name, id)
19
+
20
+ fun toExtras(): Bundle = Bundle().apply {
21
+ putString(EXTRA_NAME, name)
22
+ putString(EXTRA_ID, id)
23
+ props?.let { putString(EXTRA_PROPS, WidgetsJson.stringifyMap(it)) }
24
+ putBundle(EXTRA_OPTIONS, options.toBundle())
25
+ }
26
+
27
+ companion object {
28
+ private const val TAG_PREFIX = "expo_widgets_notification:"
29
+ private const val EXTRA_NAME = "expo.modules.widgets.notification.NAME"
30
+ private const val EXTRA_ID = "expo.modules.widgets.notification.ID"
31
+ private const val EXTRA_PROPS = "expo.modules.widgets.notification.PROPS"
32
+ private const val EXTRA_OPTIONS = "expo.modules.widgets.notification.OPTIONS"
33
+
34
+ fun tag(name: String, id: String): String = "$TAG_PREFIX${Uri.encode(name)}:${Uri.encode(id)}"
35
+
36
+ fun fromNotification(notification: Notification): CustomNotificationState? {
37
+ val extras = notification.extras ?: return null
38
+ val name = extras.getString(EXTRA_NAME) ?: return null
39
+ val id = extras.getString(EXTRA_ID) ?: return null
40
+ val props = extras.getString(EXTRA_PROPS)?.let { json ->
41
+ runCatching { WidgetsJson.parseMap(json) }.getOrNull()
42
+ }
43
+ val options = extras.getBundle(EXTRA_OPTIONS)?.let(CustomNotificationOptions::fromBundle) ?: CustomNotificationOptions()
44
+ return CustomNotificationState(name, id, props, options)
45
+ }
46
+
47
+ fun all(context: Context): List<CustomNotificationState> {
48
+ return activeStatusBarNotifications(context)
49
+ .filter { it.tag?.startsWith(TAG_PREFIX) == true }
50
+ .mapNotNull { fromNotification(it.notification) }
51
+ }
52
+
53
+ fun find(context: Context, name: String, id: String): CustomNotificationState? {
54
+ val tag = tag(name, id)
55
+ return activeStatusBarNotifications(context)
56
+ .firstOrNull { it.tag == tag }
57
+ ?.let { fromNotification(it.notification) }
58
+ }
59
+
60
+ private fun activeStatusBarNotifications(context: Context): Array<StatusBarNotification> {
61
+ val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
62
+ return runCatching { manager.activeNotifications }.getOrDefault(emptyArray())
63
+ }
64
+ }
65
+ }
@@ -0,0 +1,107 @@
1
+ package expo.modules.widgets.notifications
2
+
3
+ import android.annotation.SuppressLint
4
+ import android.content.Context
5
+ import androidx.core.app.NotificationManagerCompat
6
+ import io.github.jakex7.peek.notification.PeekNotificationViews
7
+ import kotlinx.coroutines.CancellationException
8
+ import kotlinx.coroutines.Job
9
+ import kotlinx.coroutines.coroutineScope
10
+ import kotlinx.coroutines.ensureActive
11
+ import kotlinx.coroutines.job
12
+ import kotlinx.coroutines.joinAll
13
+ import kotlin.coroutines.coroutineContext
14
+
15
+ internal class CustomNotifications(
16
+ private val render: suspend (Context, CustomNotificationState) -> PeekNotificationViews = CustomNotificationRenderer::render
17
+ ) {
18
+ private val pending = mutableMapOf<Pair<String, String>, MutableSet<Job>>()
19
+
20
+ suspend fun post(context: Context, state: CustomNotificationState) {
21
+ inOrder(state.name, state.id) {
22
+ publish(context, state)
23
+ }
24
+ }
25
+
26
+ suspend fun update(
27
+ context: Context,
28
+ name: String,
29
+ id: String,
30
+ transform: (CustomNotificationState) -> CustomNotificationState?
31
+ ): Boolean = inOrder(name, id) {
32
+ val active = CustomNotificationState.find(context, name, id) ?: return@inOrder false
33
+ val updated = transform(active) ?: return@inOrder false
34
+ publish(context, updated, requireActive = true)
35
+ }
36
+
37
+ fun cancel(context: Context, name: String, id: String) {
38
+ synchronized(pending) {
39
+ pending.remove(name to id)?.forEach { it.cancel(NotificationCancellation()) }
40
+ NotificationManagerCompat.from(context).cancel(CustomNotificationState.tag(name, id), 0)
41
+ }
42
+ }
43
+
44
+ fun cancelAll(context: Context, name: String) {
45
+ synchronized(pending) {
46
+ val ids = CustomNotificationState.all(context).filter { it.name == name }.map { it.id } +
47
+ pending.keys.filter { it.first == name }.map { it.second }
48
+ ids.toSet().forEach { cancel(context, name, it) }
49
+ }
50
+ }
51
+
52
+ @SuppressLint("MissingPermission")
53
+ private suspend fun publish(
54
+ context: Context,
55
+ state: CustomNotificationState,
56
+ requireActive: Boolean = false
57
+ ): Boolean {
58
+ val manager = NotificationManagerCompat.from(context)
59
+ if (!manager.areNotificationsEnabled()) {
60
+ throw NotificationsDisabledException()
61
+ }
62
+ val views = render(context, state)
63
+ val notification = CustomNotificationBuilder.build(context, state, views)
64
+ return synchronized(pending) {
65
+ // Cancellation and posting must not interleave after the render finishes.
66
+ coroutineContext.ensureActive()
67
+ if (requireActive && CustomNotificationState.find(context, state.name, state.id) == null) {
68
+ false
69
+ } else {
70
+ manager.notify(state.tag, 0, notification)
71
+ true
72
+ }
73
+ }
74
+ }
75
+
76
+ private suspend fun <T> inOrder(name: String, id: String, block: suspend () -> T): T = try {
77
+ coroutineScope {
78
+ val key = name to id
79
+ val job = coroutineContext.job
80
+ val previous = synchronized(pending) {
81
+ val jobs = pending.getOrPut(key) { mutableSetOf() }
82
+ jobs.toList().also { jobs.add(job) }
83
+ }
84
+ try {
85
+ // Wait for all earlier jobs: cancelling a queued job must not let later work skip ahead.
86
+ previous.joinAll()
87
+ ensureActive()
88
+ block()
89
+ } finally {
90
+ synchronized(pending) {
91
+ pending[key]?.let { jobs ->
92
+ jobs.remove(job)
93
+ if (jobs.isEmpty()) pending.remove(key)
94
+ }
95
+ }
96
+ }
97
+ }
98
+ } catch (_: NotificationCancellation) {
99
+ throw CustomNotificationCancelledException()
100
+ }
101
+
102
+ private class NotificationCancellation : CancellationException()
103
+
104
+ companion object {
105
+ val shared = CustomNotifications()
106
+ }
107
+ }
@@ -0,0 +1,67 @@
1
+ package expo.modules.widgets.notifications
2
+
3
+ import android.content.BroadcastReceiver
4
+ import android.content.Context
5
+ import android.content.Intent
6
+ import android.util.Log
7
+ import expo.modules.widgets.NOTIFICATION_INTERACTION_ACTION
8
+ import expo.modules.widgets.WIDGET_INTERACTION_NOTIFICATION_ID_EXTRA
9
+ import expo.modules.widgets.WIDGET_INTERACTION_SOURCE_EXTRA
10
+ import expo.modules.widgets.WIDGET_INTERACTION_TARGET_EXTRA
11
+ import expo.modules.widgets.WidgetsEvents
12
+ import expo.modules.widgets.WidgetsStorage
13
+ import expo.modules.widgets.evaluateWidgetButtonPress
14
+ import expo.modules.widgets.getWidgetEnvironment
15
+ import kotlinx.coroutines.CancellationException
16
+ import kotlinx.coroutines.CoroutineName
17
+ import kotlinx.coroutines.CoroutineScope
18
+ import kotlinx.coroutines.Dispatchers
19
+ import kotlinx.coroutines.SupervisorJob
20
+ import kotlinx.coroutines.launch
21
+
22
+ class ExpoWidgetsNotificationReceiver : BroadcastReceiver() {
23
+ override fun onReceive(context: Context, intent: Intent) {
24
+ if (intent.action != NOTIFICATION_INTERACTION_ACTION) {
25
+ return
26
+ }
27
+ val name = intent.getStringExtra(WIDGET_INTERACTION_SOURCE_EXTRA) ?: return
28
+ val target = intent.getStringExtra(WIDGET_INTERACTION_TARGET_EXTRA) ?: return
29
+ val notificationId = intent.getStringExtra(WIDGET_INTERACTION_NOTIFICATION_ID_EXTRA) ?: return
30
+
31
+ val pendingResult = goAsync()
32
+ scope.launch {
33
+ try {
34
+ rerenderAfterPress(context.applicationContext, name, notificationId, target)
35
+ WidgetsEvents.sendUserInteraction(name, target, notificationId)
36
+ } finally {
37
+ pendingResult.finish()
38
+ }
39
+ }
40
+ }
41
+
42
+ private suspend fun rerenderAfterPress(context: Context, name: String, notificationId: String, target: String) {
43
+ runCatching {
44
+ CustomNotifications.shared.update(context, name, notificationId) { active ->
45
+ val layout = WidgetsStorage.getString(context, "__expo_widgets_notification_${name}_layout")
46
+ ?.takeIf { it.isNotEmpty() } ?: return@update null
47
+ val environment = getWidgetEnvironment(context) + ("target" to target)
48
+ val updatedProps = evaluateWidgetButtonPress(context, layout, active.props, environment) ?: return@update null
49
+ active.copy(props = active.props.orEmpty() + updatedProps)
50
+ }
51
+ }.onFailure { error ->
52
+ if (error is CancellationException) {
53
+ throw error
54
+ }
55
+ if (error !is CustomNotificationCancelledException) {
56
+ Log.e(TAG, "Custom notification '$notificationId' of '$name' could not be re-posted after a button press.", error)
57
+ }
58
+ }
59
+ }
60
+
61
+ private companion object {
62
+ const val TAG = "ExpoWidgets"
63
+ val scope = CoroutineScope(
64
+ Dispatchers.Default + SupervisorJob() + CoroutineName("expo.widgets.NotificationReceiverScope")
65
+ )
66
+ }
67
+ }
@@ -0,0 +1,4 @@
1
+ <?xml version="1.0" encoding="utf-8"?>
2
+ <resources>
3
+ <string name="expo_widgets_notification_channel_name">Notifications</string>
4
+ </resources>
@@ -0,0 +1,128 @@
1
+ import type { CustomNotificationComponent, CustomNotificationOptions, CustomNotificationUpdateOptions, NativeCustomNotification } from './CustomNotifications.types';
2
+ /**
3
+ * A posted custom notification. It wraps a native object that knows the notification key, so an
4
+ * instance recovered with `CustomNotificationFactory.get()` or `getActive()` after a process restart
5
+ * behaves like the one returned by `post()`.
6
+ * @platform android
7
+ */
8
+ export declare class CustomNotification<T extends object = object> {
9
+ /** @hidden */
10
+ private readonly nativeNotification;
11
+ /** @hidden */
12
+ constructor(nativeNotification: NativeCustomNotification);
13
+ /**
14
+ * The key of the notification, as passed to or generated by `post()`.
15
+ * @platform android
16
+ */
17
+ get id(): string;
18
+ /**
19
+ * Reads the props currently shown by the notification from the active notification, so they
20
+ * include changes made by button presses inside the notification.
21
+ *
22
+ * Rejects when the notification is no longer active, for example after dismissal or cancellation.
23
+ * @returns A promise that resolves to the current props.
24
+ * @platform android
25
+ */
26
+ getProps(): Promise<T>;
27
+ /**
28
+ * Renders the layout with new props and replaces the notification in place. The notification
29
+ * does not alert again when `alertOnlyOnce` is `true`.
30
+ *
31
+ * Rejects when the notification is no longer active, for example after the user dismissed it or
32
+ * after `cancel()`. Post it again in that case. Also rejects when the notification is canceled
33
+ * while the update renders, or for the same reasons as `post()`, such as an invalid `color`.
34
+ * @param props The new props for the layout function.
35
+ * @param options Presentation options to change. Options that are omitted keep their previous value.
36
+ * @platform android
37
+ */
38
+ update(props: T, options?: CustomNotificationUpdateOptions): Promise<void>;
39
+ /**
40
+ * Removes the notification from the shade immediately.
41
+ * Cancels any pending post or update for this notification.
42
+ * @platform android
43
+ */
44
+ cancel(): Promise<void>;
45
+ }
46
+ /**
47
+ * Posts and manages custom notifications that share one layout.
48
+ * @platform android
49
+ */
50
+ export declare class CustomNotificationFactory<T extends object = object> {
51
+ /**
52
+ * The name passed to `createCustomNotification()`.
53
+ * @platform android
54
+ */
55
+ readonly name: string;
56
+ /** @hidden */
57
+ private readonly nativeFactory;
58
+ /** @hidden */
59
+ constructor(name: string, layout: CustomNotificationComponent<T>);
60
+ /**
61
+ * Renders the layout and posts the notification. Posting with the `id` of an active notification
62
+ * replaces that notification in place.
63
+ *
64
+ * Rejects in these cases:
65
+ * - Notifications are disabled for the app.
66
+ * - `channelId` names a channel that does not exist.
67
+ * - `smallIcon` names a drawable that does not exist.
68
+ * - `color` is not in `#RRGGBB` or `#AARRGGBB` format.
69
+ * - The layout returns no `collapsed` section.
70
+ * - The post is canceled before rendering finishes.
71
+ * @param props The props for the layout function.
72
+ * @param options Presentation options.
73
+ * @returns A promise that resolves to a handle for the posted notification.
74
+ * @platform android
75
+ */
76
+ post(props: T, options?: CustomNotificationOptions): Promise<CustomNotification<T>>;
77
+ /**
78
+ * Returns the active notification with the given key.
79
+ * @param id The key passed to or generated by `post()`.
80
+ * @returns A promise that resolves to the notification, or to `null` when no such notification is active.
81
+ * @platform android
82
+ */
83
+ get(id: string): Promise<CustomNotification<T> | null>;
84
+ /**
85
+ * Returns every active notification posted with this layout, including notifications posted
86
+ * before a process restart.
87
+ * @platform android
88
+ */
89
+ getActive(): Promise<CustomNotification<T>[]>;
90
+ /**
91
+ * Removes every active notification posted with this layout and cancels pending posts and updates.
92
+ * @platform android
93
+ */
94
+ cancelAll(): Promise<void>;
95
+ private requireNativeFactory;
96
+ }
97
+ /**
98
+ * Creates a factory that posts notifications rendered from the given layout.
99
+ *
100
+ * The factory can be created on every platform. Its methods reject with `UnavailabilityError` on
101
+ * platforms other than Android.
102
+ * @param name A unique name for the layout. It identifies the layout when a notification button
103
+ * is pressed and when active notifications are recovered.
104
+ * @param layout The layout component, marked with the `'widget'` directive.
105
+ * @example
106
+ * ```tsx
107
+ * import { Row, Text } from '@expo/ui/jetpack-compose';
108
+ * import { createCustomNotification } from 'expo-widgets';
109
+ *
110
+ * type Props = { status: string };
111
+ *
112
+ * const OrderNotification = createCustomNotification('OrderNotification', (props: Props) => {
113
+ * 'widget';
114
+ * return {
115
+ * collapsed: (
116
+ * <Row>
117
+ * <Text>{props.status}</Text>
118
+ * </Row>
119
+ * ),
120
+ * };
121
+ * });
122
+ *
123
+ * const order = await OrderNotification.post({ status: 'Preparing' }, { id: 'order-1', ongoing: true });
124
+ * await order.update({ status: 'Delivered' }, { ongoing: false, timeoutAfter: 15 * 60 * 1000 });
125
+ * ```
126
+ * @platform android
127
+ */
128
+ export declare function createCustomNotification<T extends object = object>(name: string, layout: CustomNotificationComponent<T>): CustomNotificationFactory<T>;
@@ -0,0 +1,162 @@
1
+ import { UnavailabilityError, uuid } from 'expo';
2
+ import { Platform } from 'react-native';
3
+ import ExpoWidgetsModule from './ExpoWidgets';
4
+ /**
5
+ * A posted custom notification. It wraps a native object that knows the notification key, so an
6
+ * instance recovered with `CustomNotificationFactory.get()` or `getActive()` after a process restart
7
+ * behaves like the one returned by `post()`.
8
+ * @platform android
9
+ */ export class CustomNotification {
10
+ /** @hidden */ nativeNotification;
11
+ /** @hidden */ constructor(nativeNotification){
12
+ this.nativeNotification = nativeNotification;
13
+ }
14
+ /**
15
+ * The key of the notification, as passed to or generated by `post()`.
16
+ * @platform android
17
+ */ get id() {
18
+ return this.nativeNotification.getId();
19
+ }
20
+ /**
21
+ * Reads the props currently shown by the notification from the active notification, so they
22
+ * include changes made by button presses inside the notification.
23
+ *
24
+ * Rejects when the notification is no longer active, for example after dismissal or cancellation.
25
+ * @returns A promise that resolves to the current props.
26
+ * @platform android
27
+ */ async getProps() {
28
+ return await this.nativeNotification.getProps();
29
+ }
30
+ /**
31
+ * Renders the layout with new props and replaces the notification in place. The notification
32
+ * does not alert again when `alertOnlyOnce` is `true`.
33
+ *
34
+ * Rejects when the notification is no longer active, for example after the user dismissed it or
35
+ * after `cancel()`. Post it again in that case. Also rejects when the notification is canceled
36
+ * while the update renders, or for the same reasons as `post()`, such as an invalid `color`.
37
+ * @param props The new props for the layout function.
38
+ * @param options Presentation options to change. Options that are omitted keep their previous value.
39
+ * @platform android
40
+ */ update(props, options = {}) {
41
+ return this.nativeNotification.update(props, toNativeOptions(options));
42
+ }
43
+ /**
44
+ * Removes the notification from the shade immediately.
45
+ * Cancels any pending post or update for this notification.
46
+ * @platform android
47
+ */ cancel() {
48
+ return this.nativeNotification.cancel();
49
+ }
50
+ }
51
+ /**
52
+ * Posts and manages custom notifications that share one layout.
53
+ * @platform android
54
+ */ export class CustomNotificationFactory {
55
+ /**
56
+ * The name passed to `createCustomNotification()`.
57
+ * @platform android
58
+ */ name;
59
+ /** @hidden */ nativeFactory;
60
+ /** @hidden */ constructor(name, layout){
61
+ this.name = name;
62
+ this.nativeFactory = Platform.OS === 'android' ? new ExpoWidgetsModule.CustomNotificationFactory(name, layout) : null;
63
+ }
64
+ /**
65
+ * Renders the layout and posts the notification. Posting with the `id` of an active notification
66
+ * replaces that notification in place.
67
+ *
68
+ * Rejects in these cases:
69
+ * - Notifications are disabled for the app.
70
+ * - `channelId` names a channel that does not exist.
71
+ * - `smallIcon` names a drawable that does not exist.
72
+ * - `color` is not in `#RRGGBB` or `#AARRGGBB` format.
73
+ * - The layout returns no `collapsed` section.
74
+ * - The post is canceled before rendering finishes.
75
+ * @param props The props for the layout function.
76
+ * @param options Presentation options.
77
+ * @returns A promise that resolves to a handle for the posted notification.
78
+ * @platform android
79
+ */ async post(props, options = {}) {
80
+ const nativeFactory = this.requireNativeFactory('post');
81
+ const id = options.id ?? uuid.v4();
82
+ const nativeNotification = await nativeFactory.post(id, props, toNativeOptions({
83
+ ...options,
84
+ ongoing: options.ongoing ?? false,
85
+ alertOnlyOnce: options.alertOnlyOnce ?? true
86
+ }));
87
+ return new CustomNotification(nativeNotification);
88
+ }
89
+ /**
90
+ * Returns the active notification with the given key.
91
+ * @param id The key passed to or generated by `post()`.
92
+ * @returns A promise that resolves to the notification, or to `null` when no such notification is active.
93
+ * @platform android
94
+ */ async get(id) {
95
+ const nativeNotification = await this.requireNativeFactory('get').get(id);
96
+ return nativeNotification ? new CustomNotification(nativeNotification) : null;
97
+ }
98
+ /**
99
+ * Returns every active notification posted with this layout, including notifications posted
100
+ * before a process restart.
101
+ * @platform android
102
+ */ async getActive() {
103
+ const nativeNotifications = await this.requireNativeFactory('getActive').getActive();
104
+ return nativeNotifications.map((nativeNotification)=>new CustomNotification(nativeNotification));
105
+ }
106
+ /**
107
+ * Removes every active notification posted with this layout and cancels pending posts and updates.
108
+ * @platform android
109
+ */ async cancelAll() {
110
+ await this.requireNativeFactory('cancelAll').cancelAll();
111
+ }
112
+ requireNativeFactory(methodName) {
113
+ if (!this.nativeFactory) {
114
+ throw new UnavailabilityError('ExpoWidgets', `CustomNotificationFactory.${methodName}`);
115
+ }
116
+ return this.nativeFactory;
117
+ }
118
+ }
119
+ /**
120
+ * Creates a factory that posts notifications rendered from the given layout.
121
+ *
122
+ * The factory can be created on every platform. Its methods reject with `UnavailabilityError` on
123
+ * platforms other than Android.
124
+ * @param name A unique name for the layout. It identifies the layout when a notification button
125
+ * is pressed and when active notifications are recovered.
126
+ * @param layout The layout component, marked with the `'widget'` directive.
127
+ * @example
128
+ * ```tsx
129
+ * import { Row, Text } from '@expo/ui/jetpack-compose';
130
+ * import { createCustomNotification } from 'expo-widgets';
131
+ *
132
+ * type Props = { status: string };
133
+ *
134
+ * const OrderNotification = createCustomNotification('OrderNotification', (props: Props) => {
135
+ * 'widget';
136
+ * return {
137
+ * collapsed: (
138
+ * <Row>
139
+ * <Text>{props.status}</Text>
140
+ * </Row>
141
+ * ),
142
+ * };
143
+ * });
144
+ *
145
+ * const order = await OrderNotification.post({ status: 'Preparing' }, { id: 'order-1', ongoing: true });
146
+ * await order.update({ status: 'Delivered' }, { ongoing: false, timeoutAfter: 15 * 60 * 1000 });
147
+ * ```
148
+ * @platform android
149
+ */ export function createCustomNotification(name, layout) {
150
+ return new CustomNotificationFactory(name, layout);
151
+ }
152
+ // Strip omitted values so native updates preserve the previous options.
153
+ function toNativeOptions(options) {
154
+ const { id: _id, ongoing, autoCancel, ...rest } = options;
155
+ return Object.fromEntries(Object.entries({
156
+ ...rest,
157
+ ongoing,
158
+ autoCancel: autoCancel ?? (ongoing === undefined ? undefined : !ongoing)
159
+ }).filter(([, value])=>value !== undefined));
160
+ }
161
+
162
+ //# sourceMappingURL=CustomNotifications.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["CustomNotifications.ts"],"sourcesContent":[null],"names":["UnavailabilityError","uuid","Platform","ExpoWidgetsModule","CustomNotification","nativeNotification","id","getId","getProps","update","props","options","toNativeOptions","cancel","CustomNotificationFactory","name","nativeFactory","layout","OS","post","requireNativeFactory","v4","ongoing","alertOnlyOnce","get","getActive","nativeNotifications","map","cancelAll","methodName","createCustomNotification","_id","autoCancel","rest","Object","fromEntries","entries","undefined","filter","value"],"mappings":"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"}
@@ -0,0 +1,124 @@
1
+ import { SharedObject } from 'expo';
2
+ import type { ReactNode } from 'react';
3
+ /**
4
+ * The views of a custom notification. Each section is rendered into its own `RemoteViews` at a
5
+ * fixed size, so a section cannot depend on the size of another section.
6
+ * @platform android
7
+ */
8
+ export type CustomNotificationLayout = {
9
+ /**
10
+ * The collapsed row shown in the notification shade. The system gives it about 64
11
+ * density-independent pixels (dp) of height.
12
+ */
13
+ collapsed: ReactNode;
14
+ /**
15
+ * The expanded view shown when the user expands the notification. The system gives it up to
16
+ * 256 dp of height. When omitted, the system derives the expanded view from `collapsed`.
17
+ */
18
+ expanded?: ReactNode;
19
+ /**
20
+ * The heads-up view shown when the notification peeks over the current screen. The system gives
21
+ * it about 88 dp of height. When omitted, the system reuses `collapsed`. The channel importance
22
+ * decides whether a heads-up view is shown at all.
23
+ */
24
+ headsUp?: ReactNode;
25
+ };
26
+ /**
27
+ * Values the system provides to a custom notification layout.
28
+ * @platform android
29
+ */
30
+ export type CustomNotificationEnvironment = {
31
+ /**
32
+ * The color scheme of the device at render time.
33
+ */
34
+ colorScheme: 'light' | 'dark';
35
+ };
36
+ /**
37
+ * A function that returns the views of a custom notification. It must start with the `'widget'`
38
+ * directive and use `@expo/ui/jetpack-compose` components.
39
+ * @platform android
40
+ */
41
+ export type CustomNotificationComponent<T extends object = object> = (props: T, environment: CustomNotificationEnvironment) => CustomNotificationLayout;
42
+ /**
43
+ * Presentation options of a custom notification.
44
+ * @platform android
45
+ */
46
+ export type CustomNotificationOptions = {
47
+ /**
48
+ * The key of the notification. Posting with the key of an active notification replaces that
49
+ * notification in place. Defaults to a random UUID.
50
+ */
51
+ id?: string;
52
+ /**
53
+ * The notification channel the notification is posted to. The channel must exist, for example,
54
+ * one created with `expo-notifications`. Defaults to a low-importance channel with the ID
55
+ * `expo_widgets_notifications`, which `expo-widgets` creates on first use. The system settings
56
+ * list it as "Notifications".
57
+ */
58
+ channelId?: string;
59
+ /**
60
+ * The content title. Screen readers announce it, and the system uses it when it cannot show the
61
+ * custom views.
62
+ */
63
+ title?: string;
64
+ /**
65
+ * The content text. The system uses it when it cannot show the custom views.
66
+ */
67
+ text?: string;
68
+ /**
69
+ * Whether the user cannot dismiss the notification with a swipe.
70
+ * @default false
71
+ */
72
+ ongoing?: boolean;
73
+ /**
74
+ * Whether a tap removes the notification. Defaults to the opposite of `ongoing`.
75
+ */
76
+ autoCancel?: boolean;
77
+ /**
78
+ * Whether sound, vibration, and the heads-up view are used only for the first post and not for
79
+ * updates.
80
+ * @default true
81
+ */
82
+ alertOnlyOnce?: boolean;
83
+ /**
84
+ * Time in milliseconds after which the system removes the notification. Useful after a final
85
+ * update that sets `ongoing` to `false`.
86
+ */
87
+ timeoutAfter?: number;
88
+ /**
89
+ * A deep link opened in this app when the user taps the notification. Defaults to the launch
90
+ * intent of the app.
91
+ */
92
+ url?: string;
93
+ /**
94
+ * The name of a drawable resource used as the small icon. Defaults to the icon configured by
95
+ * the `expo-notifications` config plugin, and then to the app icon.
96
+ */
97
+ smallIcon?: string;
98
+ /**
99
+ * The accent color in `#RRGGBB` or `#AARRGGBB` format. Defaults to the color configured by the
100
+ * `expo-notifications` config plugin.
101
+ */
102
+ color?: string;
103
+ };
104
+ /**
105
+ * Presentation options that an update can override. Options that an update omits keep the value
106
+ * from the previous post or update.
107
+ * @platform android
108
+ */
109
+ export type CustomNotificationUpdateOptions = Omit<CustomNotificationOptions, 'id'>;
110
+ /** @hidden */
111
+ export declare class NativeCustomNotification extends SharedObject {
112
+ getId(): string;
113
+ getProps(): Promise<Record<string, any>>;
114
+ update(props: Record<string, any>, options: CustomNotificationUpdateOptions): Promise<void>;
115
+ cancel(): Promise<void>;
116
+ }
117
+ /** @hidden */
118
+ export declare class NativeCustomNotificationFactory extends SharedObject {
119
+ constructor(name: string, layout: string);
120
+ post(id: string, props: Record<string, any>, options: CustomNotificationUpdateOptions): Promise<NativeCustomNotification>;
121
+ get(id: string): Promise<NativeCustomNotification | null>;
122
+ getActive(): Promise<NativeCustomNotification[]>;
123
+ cancelAll(): Promise<void>;
124
+ }
@@ -0,0 +1,3 @@
1
+ import { SharedObject } from 'expo';
2
+
3
+ //# sourceMappingURL=CustomNotifications.types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["CustomNotifications.types.ts"],"sourcesContent":[null],"names":["SharedObject"],"mappings":"AAAA,SAASA,YAAY,QAAQ,OAAO"}