WebNotification.java
16.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
package com.burokrat.notifications;
import com.vaadin.annotations.JavaScript;
import com.vaadin.server.AbstractJavaScriptExtension;
import com.vaadin.ui.Component;
import com.vaadin.ui.JavaScriptFunction;
import com.vaadin.ui.UI;
import elemental.json.JsonArray;
import elemental.json.JsonObject;
import elemental.json.JsonValue;
import elemental.json.impl.JreJsonFactory;
import java.lang.ref.WeakReference;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* This is a Vaadin extension to support the (Web) Notifications API. This allows you to show
* notifications directly on the user's desktop, regardless of whether browser or browser tab are
* currently visible.
* <p>
* There are two competing specifications for this API: one from the
* <a href="https://notifications.spec.whatwg.org/">WHATWG</a> and one from the
* <a href="https://www.w3.org/TR/notifications/">W3C</a>. They share features, but there are
* differences. And differing browser support on different platforms makes the situation even more
* complicated. That's an abyss that I didn't want to fully explore.
* <p>
* If you just want to show notifications without getting down to the nitty-gritty of browser
* support, the following options should be rather safe to use - at least in desktop browsers:
* <ul>
* <li>{@link NotificationBuilder#body(String) body}</li>
* <li>{@link NotificationBuilder#icon(String) icon}</li>
* <li>{@link NotificationBuilder#tag(String) tag}</li>
* <li>{@link NotificationBuilder#timeout(Integer) timeout}</li>
* <li>{@link NotificationBuilder#closeOnClick(boolean) closeOnClick}</li>
* <li>{@link NotificationBuilder#focusOnClick(boolean) focusOnClick}</li>
* </ul>
* <p>
* This extension needs to be attached to a UI and needs to request the user's permission to show
* notifications. However all that is taken care of automatically.
* <p>
* Uses <a href="https://github.com/alexgibson/notify.js">notify.js</a> by
* <a href="http://alxgbsn.co.uk/">Alex Gibson</a>.
*/
@JavaScript({"WebNotificationsConnector.js", "notify.js"})
public class WebNotification
extends AbstractJavaScriptExtension {
/*
* The weak references ensure there are no memory leaks, as there is no safe hook for cleaning up
* the callbacks. It's possible that the callback is garbage collected too early, but considering
* the usually limited lifespan of a notification, the chances for that should be slim. And I'd
* rather deal with that than a memory leak.
*/
private ConcurrentMap<String, WeakReference<Callbacks>> callbacks = new ConcurrentHashMap<>();
/**
* Registers the {@link WebNotification} extension with the given UI.
*
* @param ui the UI
*/
private WebNotification(UI ui) {
extend(ui);
addFunction("onClickCallback", new JavaScriptFunction() {
@Override
public void call(JsonArray arguments) {
onClick(arguments);
}
});
addFunction("onErrorCallback", new JavaScriptFunction() {
@Override
public void call(JsonArray arguments) {
onError(arguments);
}
});
addFunction("onCloseCallback", new JavaScriptFunction() {
@Override
public void call(JsonArray arguments) {
onClose(arguments);
}
});
}
/**
* Creates a notification and returns a {@link NotificationBuilder} to further customize the
* notification before actually {@link NotificationBuilder#show() showing} it.
* {@link UI#getCurrent()} is used to determine the UI.
*
* @param title the title of the notification
* @return the {@link NotificationBuilder} to customize the notification before showing it
*/
public static NotificationBuilder create(String title) {
UI ui = UI.getCurrent();
if (ui == null)
throw new IllegalStateException("no current UI found");
return create(ui, title);
}
/**
* Creates a notification and returns a {@link NotificationBuilder} to further customize the
* notification before actually {@link NotificationBuilder#show() showing} it.
*
* @param component the component that wishes to show a notification or at least the component that is
* used to determine the UI; can be the UI itself
* @param title the title of the notification
* @return the {@link NotificationBuilder} to customize the notification before showing it
*/
public static NotificationBuilder create(Component component, String title) {
Objects.requireNonNull(component, "component");
Objects.requireNonNull(title, "title");
UI ui = component.getUI();
if (ui == null)
throw new IllegalStateException("the component is not attached to a UI");
WebNotification webnot = new WebNotification(ui);
return webnot.doCreate(title);
}
/**
* @param title the title of the notification
* @return the {@link NotificationBuilder} to customize the notification before showing it
*/
private NotificationBuilder doCreate(String title) {
return new NotificationBuilder(title);
}
private void onClick(JsonArray arguments) {
String notificationId = arguments.getString(0);
WeakReference<Callbacks> ref = this.callbacks.remove(notificationId);
if (ref == null)
return;
Callbacks callbacks = ref.get();
if (callbacks == null)
return;
if (callbacks.onClick == null)
return;
callbacks.onClick.run();
}
private void onError(JsonArray arguments) {
String notificationId = arguments.getString(0);
WeakReference<Callbacks> ref = this.callbacks.remove(notificationId);
if (ref == null)
return;
Callbacks callbacks = ref.get();
if (callbacks == null)
return;
if (callbacks.onError == null)
return;
callbacks.onError.run();
}
private void onClose(JsonArray arguments) {
/**
* Considering the deprecated nature of onclose, it's not officially supported here. But as long
* as browsers support it anyway, it's used to explicitly clean up callbacks.
*/
String notificationId = arguments.getString(0);
this.callbacks.remove(notificationId);
}
public class NotificationBuilder {
// used to find registered callbacks
private String notificationId = UUID.randomUUID().toString();
private String title;
private NotificationDirection dir = NotificationDirection.auto;
private String lang = "";
private String body = "";
private String tag = "";
private String image;
private String icon;
private String badge;
private String sound;
//private Instant timestamp;
private Boolean renotify = false;
private Boolean silent = false;
private Boolean requireInteraction = false;
private String data;
private Runnable onClickCallback;
private Runnable onErrorCallback;
private Integer timeout;
private boolean closeOnClick = false;
private boolean focusOnClick = false;
private NotificationBuilder(String title) {
this.title = Objects.requireNonNull(title);
}
String getNotificationId() {
return notificationId;
}
public NotificationBuilder dir(NotificationDirection dir) {
this.dir = dir != null ? dir : NotificationDirection.auto;
return this;
}
public NotificationBuilder lang(String lang) {
this.lang = lang != null ? lang : "";
return this;
}
/**
* The notification's body.
*
* @param body the notification's body
* @return this notification builder
*/
public NotificationBuilder body(String body) {
this.body = body != null ? body : "";
return this;
}
/**
* <a href="https://notifications.spec.whatwg.org/#tags-example">A notification is considered to
* be replaceable if there is a notification in the list of notifications whose tag is not the
* empty string and equals the notification’s tag, and whose origin is same origin with
* notification’s origin.</a>
* <p>
* Basically, notifications with the same tag will replace each other.
*
* @param tag the tag
* @return this notification builder
*/
public NotificationBuilder tag(String tag) {
this.tag = tag != null ? tag : "";
return this;
}
/**
* <a href="https://notifications.spec.whatwg.org/#image-resource">An image resource is a
* picture shown as part of the content of the notification, and should be displayed with higher
* visual priority than the icon resource and badge resource, though it may be displayed in
* fewer circumstances.</a>
* <p>
* Supports normals protocols as well as Vaadin-specific protocols like {@code theme://}.
*
* @param imageUrl the image URL
* @return this notification builder
*/
public NotificationBuilder image(String imageUrl) {
this.image = imageUrl;
return this;
}
/**
* <a href="https://notifications.spec.whatwg.org/#icon-resource">An image that reinforces the
* notification (such as an icon, or a photo of the sender).</a>
* <p>
* Supports normals protocols as well as Vaadin-specific protocols like {@code theme://}.
*
* @param iconUrl the icon URL
* @return this notification builder
*/
public NotificationBuilder icon(String iconUrl) {
this.icon = iconUrl;
return this;
}
/**
* <a href="https://notifications.spec.whatwg.org/#badge-resource">A badge resource is an icon
* representing the web application, or the category of the notification if the web application
* sends a wide variety of notifications. It may be used to represent the notification when
* there is not enough space to display the notification itself. It may also be displayed inside
* the notification, but then it should have less visual priority than the image resource and
* icon resource.</a>
* <p>
* Supports normals protocols as well as Vaadin-specific protocols like {@code theme://}.
*
* @param badgeUrl the badge URL
* @return this notification builder
*/
public NotificationBuilder badge(String badgeUrl) {
this.badge = badgeUrl;
return this;
}
/*public NotificationBuilder timestamp(Instant timestamp)
{
this.timestamp = timestamp;
return this;
}*/
public NotificationBuilder renotify(Boolean renotify) {
this.renotify = renotify;
return this;
}
public NotificationBuilder silent(Boolean silent) {
this.silent = silent;
return this;
}
public NotificationBuilder requireInteraction(Boolean requireInteraction) {
this.requireInteraction = requireInteraction;
return this;
}
/**
* Sets an explicit timeout after which the notification will be programmatically closed.
* Browsers will typically close them on their own after a while, so setting this should not be
* necessary. I.e. this cannot increase the browser's own timeout, only beat it to it.
*
* @param timeout the timeout in seconds
* @return this notification builder
*/
public NotificationBuilder timeout(Integer timeout) {
this.timeout = timeout;
return this;
}
/**
* Whether the notification should be closed when clicked. This makes notifications easier to
* get rid of in browsers where this isn't the default behavior already.
*
* @param closeOnClick whether to close on click
* @return this notification builder
*/
public NotificationBuilder closeOnClick(boolean closeOnClick) {
this.closeOnClick = closeOnClick;
return this;
}
/**
* Whether clicking the notification should focus the browser window and the application's
* browser tab. This should also bring the browser window to the front, even if it's currently
* minimized; although that part didn't work in Edge for me.
*
* @param focusOnClick whether to close on click
* @return this notification builder
*/
public NotificationBuilder focusOnClick(boolean focusOnClick) {
this.focusOnClick = focusOnClick;
return this;
}
/**
* The callback when the notification is clicked.
*
* @param onClickCallback the onClick callback
* @return this notification builder
*/
public NotificationBuilder onClick(Runnable onClickCallback) {
this.onClickCallback = onClickCallback;
return this;
}
Runnable getOnClickCallback() {
return onClickCallback;
}
/**
* The callback when the notification could not be shown for some reason.
*
* @param onErrorCallback the onError callback
* @return this notification builder
*/
public NotificationBuilder onError(Runnable onErrorCallback) {
this.onErrorCallback = onErrorCallback;
return this;
}
Runnable getOnErrorCallback() {
return onErrorCallback;
}
/**
* Shows the notification.
*/
public void show() {
if (getOnClickCallback() != null || getOnErrorCallback() != null) {
callbacks.put(getNotificationId(),
new WeakReference<>(new Callbacks(getOnClickCallback(), getOnErrorCallback())));
}
getUI().access(new Runnable() {
@Override
public void run() {
callFunction("show", title, toOptionsJson());
}
});
}
/**
* Creates the options object that will be passed to the notification.
*
* @return the options object that will be passed to the notification
*/
JsonValue toOptionsJson() {
JreJsonFactory factory = new JreJsonFactory();
JsonObject options = factory.createObject();
// custom property used to map back to correct callbacks
options.put("notificationId", notificationId);
options.put("dir", dir.name());
options.put("lang", lang);
options.put("body", body);
options.put("tag", tag);
if (image != null)
options.put("image", image);
if (icon != null)
options.put("icon", icon);
if (badge != null)
options.put("badge", badge);
if (sound != null)
options.put("sound", sound);
/*if (timestamp != null)
options.put("timestamp", timestamp.toEpochMilli());*/
options.put("renotify", renotify);
options.put("silent", silent);
options.put("requireInteraction", requireInteraction);
if (data != null)
options.put("data", data);
// custom options offered by notify.js
if (timeout != null)
options.put("timeout", timeout);
options.put("closeOnClick", closeOnClick);
// custom properties
options.put("focusOnClick", focusOnClick);
options.put("hasOnClick", onClickCallback != null);
options.put("hasOnError", onErrorCallback != null);
return options;
}
}
public enum NotificationDirection {
auto,
ltr,
rtl
}
private static class Callbacks {
private Runnable onClick;
private Runnable onError;
private Callbacks(Runnable onClick, Runnable onError) {
super();
this.onClick = onClick;
this.onError = onError;
}
}
/*@FunctionalInterface
public interface SerializableRunnable extends Serializable, Runnable
{
}*/
}