/
Polymer.java
590 lines (522 loc) · 19.7 KB
/
Polymer.java
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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
package com.vaadin.polymer;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JavaScriptObject;
import elemental2.core.JsArray;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.Element;
import com.google.gwt.user.client.DOM;
import com.vaadin.polymer.PolymerFunction;
import elemental2.dom.HTMLElement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static jsinterop.annotations.JsPackage.GLOBAL;
import jsinterop.annotations.JsPackage;
import jsinterop.annotations.JsProperty;
import jsinterop.annotations.JsType;
import jsinterop.base.Js;
@SuppressWarnings({"rawtypes", "unchecked"})
public abstract class Polymer {
private static PolymerRoot Polymer;
public static Base Base;
private static boolean hasHtmlImports = htmlImportsSupported();
/**
* Set the location of the bower_components for the application.
* By default it is computed from the module base.
*
* Additionally this can be set from JS modifying the
* `window.gwtBowerLocation` property.
*/
@JsProperty(namespace = JsPackage.GLOBAL)
public static native void setGwtBowerLocation(String s);
@JsProperty(namespace = JsPackage.GLOBAL)
public static native String getGwtBowerLocation();
static {
if (getGwtBowerLocation() == null) {
String moduleBase = GWT.getModuleBaseForStaticFiles();
String moduleName = GWT.getModuleName();
// SSO linker does not set correctly the module base
if (!moduleBase.contains(moduleName)) {
moduleBase = moduleName + "/";
}
setGwtBowerLocation(moduleBase + "bower_components/");
}
}
@JsType(isNative=true, namespace="Polymer")
public interface DomApi {
<T extends HTMLElement> T querySelector(String selector);
JsArray querySelectorAll(String selector);
void appendChild(Object el);
JsArray children();
}
@JsType(isNative=true, namespace=GLOBAL)
public interface PolymerRoot {
void updateStyles();
DomApi dom(Object el);
}
@JsType(isNative=true, namespace="Polymer")
public interface Base {
/**
* Returns the first node in this element’s local DOM that matches selector.
*/
Element $$(String selector);
/**
* Toggles the named boolean class on the node, adding the class if bool is
* truthy and removing it if bool is falsey.
*/
void toggleClass(String name, boolean b, Element node);
/**
* Toggles the named boolean attribute on the node.
*/
void toggleAttribute(String name, boolean b, Element node);
/**
* Moves a boolean attribute from oldNode to newNode, unsetting the attribute
* (if set) on oldNode and setting it on newNode
*/
void attributeFollows(String name, Element newNode, Element oldNode);
/**
* Moves a class from oldNode to newNode, removing the class (if present)
* on oldNode and adding it to newNode.
*/
void classFollows(String name, Element newNode, Element oldNode);
/**
* Fires a custom event. The options object can contain the following properties:
* node: Node to fire the event on (defaults to this).
* bubbles: Whether the event should bubble. Defaults to true.
* cancelable: Whether the event can be canceled with preventDefault. Defaults to false.
*/
void fire(String type, JavaScriptObject detail, JavaScriptObject options);
/**
* Calls method asynchronously. If no wait time is specified, runs tasks with microtask
* timing (after the current method finishes, but before the next event from the event
* queue is processed). Returns a handle that can be used to cancel the task.
*/
Object async(PolymerFunction method, int wait);
/**
* Cancels the identified async task.
*/
void cancelAsync(Object handle);
/**
* Applies a CSS transform to the specified node, or host element if no node is
* specified. transform is specified as a string. For example:
* transform('rotateX(90deg)', elm);
*/
void transform(String transform, Element node);
/**
* Transforms the specified node, or host element if no node is specified. For example:
* translate3d('100px', '100px', '100px', elm);
*/
void translate3d(String x, String y, String z, Element node);
/**
* Dynamically imports an HTML document.
*/
void importHref(String href, PolymerFunction onload, PolymerFunction onerror);
/**
* Takes a URL relative to the <dom-module> of an imported Polymer element, and returns
* a path relative to the current document. This method can be used, for example,
* to refer to an asset delivered alongside an HTML import.
*/
String resolveUrl(String url);
}
private static Set<String> urlImported = new HashSet<>();
private static HashMap<String, List<PolymerFunction>> whenImported = new HashMap<>();
/**
* Inserts the appropriate <import> of a component given by url.
*
* @param href either an absolute url or a path relative to bower_components folder.
*/
public static void importHref(String href) {
importHref(href, null, null);
}
/**
* Inserts the appropriate <import> of a component given by url.
*
* @param href either an absolute url or a path relative to bower_components folder.
* @param ok callback to run in case of success
*/
public static void importHref(String href, PolymerFunction ok) {
importHref(href, ok, null);
}
private static String absoluteHref(String hrefOrTag) {
if (!hrefOrTag.startsWith("http")) {
// It's a tag
if (hrefOrTag.matches("[\\w-]+")) {
hrefOrTag = hrefOrTag + "/" + hrefOrTag;
}
// Not ending with html or js
if (!hrefOrTag.matches(".*\\.(html|js)$")) {
hrefOrTag += ".html";
}
hrefOrTag = getGwtBowerLocation() + hrefOrTag;
}
return hrefOrTag;
}
// Loads Polymer once if not done yet, and queue all callbaks until ready
private static native void whenPolymerLoaded(PolymerFunction ok)
/*-{
function resolve() {
// Set our static reference to Base
@com.vaadin.polymer.Polymer::Polymer = $wnd.Polymer;
@com.vaadin.polymer.Polymer::Base = $wnd.Polymer.Base;
// Polymer dynamic loaded does not remove unresolved
$doc.body.removeAttribute('unresolved');
}
if (!$wnd.Polymer) {
// Dynamic load Polymer and wait until ready
if (!$wnd._pending_oks) {
$wnd._pending_oks = [ok];
var l = $doc.createElement('link');
l.rel = 'import';
l.href = @com.vaadin.polymer.Polymer::absoluteHref(*)('polymer');
l.onload = function() {
// Run all tasks waiting for Polymer be ready
$wnd._pending_oks.forEach(function(ok){ok()});
$wnd._pending_oks = undefined;
resolve();
};
$doc.head.appendChild(l);
}
$wnd._pending_oks.push(ok);
} else {
resolve();
ok();
}
}-*/;
/**
* Inserts the appropriate <import> of a component given by url.
* If the components is already registered it does not import anything so as
* the user could import elements in the hosted page, or vulcanize them.
* If the component is being imported, all callbacks are queued until ready.
*
* @param hrefOrTag it can be an absolute url, a relative path or a tag name.
* - if it is a relative path, we prefix it with bower_components
* in case it is not already prefixed.
* - if it is a tag, we compose the relative url:
* bower_components/tagName/tagName.html
* @param ok callback to run in case of success
* @param err callback to run in case of failure
*/
public static void importHref(String hrefOrTag, final PolymerFunction ok, final PolymerFunction err) {
final String href = absoluteHref(hrefOrTag);
PolymerFunction done = arg -> {
urlImported.add(href);
List<PolymerFunction> pending = whenImported.get(href);
if (pending != null) {
for (PolymerFunction f : pending) {
f.call(null);
}
}
whenImported.remove(href);
return null;
};
if (Base == null) {
whenPolymerLoaded(arg -> {
importHref(hrefOrTag, ok, err);
return null;
});
return;
}
if (!urlImported.contains(href)) {
if (!isRegistered(href)) {
List<PolymerFunction> pending = whenImported.get(href);
if (pending == null) {
pending = new ArrayList<PolymerFunction>();
whenImported.put(href, pending);
Base.importHref(href, done, err);
}
if (ok != null) {
pending.add(ok);
}
return;
}
urlImported.add(href);
}
if (ok != null) {
ok.call(null);
}
}
/**
* Inserts the appropriate <import> of a list of components
*
* @param hrefs a list of absolute urls or relative paths to load.
*/
public static void importHref(final List<String> hrefs) {
importHref(hrefs, null, null);
}
/**
* Inserts the appropriate <import> of a list of components
*
* @param hrefs a list of absolute urls or relative paths to load.
* @param ok callback to run in case of all import success
*/
public static void importHref(final List<String> hrefs, final PolymerFunction ok) {
importHref(hrefs, ok, null);
}
/**
* Inserts the appropriate <import> of a list of components
*
* @param hrefs a list of absolute urls or relative paths to load.
* @param ok callback to run in case of all import success
* @param err callback to run in case of failure
*/
public static void importHref(final List<String> hrefs, final PolymerFunction ok, PolymerFunction err) {
PolymerFunction allOk = ok == null ? ok : new PolymerFunction() {
int count = hrefs.size();
public Object call(Object arg) {
if (--count == 0) {
ok.call(arg);
}
return null;
}
};
for (String href : hrefs) {
importHref(href, allOk, err);
}
}
/**
* Returns a new instance of the Element. It loads the web component
* from the bower_components/src url if it was not loaded yet.
*/
public static <T> T createElement(final String tagName, final String... imports) {
final T e = (T)Document.get().createElement(tagName);
if (imports.length > 0) {
ensureCustomElement(e, imports);
} else {
ensureCustomElement(e, tagName);
}
return e;
}
public static <T> void ensureCustomElement(final T elem, String... imports) {
if (isRegisteredElement(elem)) {
return;
}
// Import all necessary stuff for this element
for (String src : imports) {
importHref(src, null, null);
}
}
/**
* Returns a new instance of the Element. It loads the web component
* from the bower_components/tagName/tagName.html url if not loaded yet.
*/
public static <T> T createElement(String tagName) {
return createElement(tagName, new String[]{});
}
/**
* Returns the JsInterop instance of Document
*/
public static elemental2.dom.Document getDocument() {
return Js.cast(Document.get());
}
/**
* Return true if the element is already registered.
* Useful when components are loaded previously, i.e. when vulcanizing imports.
*/
private static boolean isRegistered(String hrefOrTag) {
Element e = Document.get().createElement(hrefOrTag.replaceFirst("^.*/(.+).html$", "$1"));
return isRegisteredElement(e);
}
/**
* Check whether a certain custom element has been registered.
*/
private native static boolean isRegisteredElement(Object e)
/*-{
return !!e && e.constructor !== $wnd.HTMLElement && e.constructor != $wnd.HTMLUnknownElement;
}-*/;
public static void ready(HTMLElement e, PolymerFunction f) {
whenReady(f, Js.cast(e));
}
public static void ready(Element e, PolymerFunction f) {
whenReady(f, e);
}
/**
* Update all style elements on the page.
*/
public static void updateStyles() {
Polymer.updateStyles();
}
/**
* Executes a function after all imports have been loaded.
*/
public static void whenReady(PolymerFunction f) {
whenReady(f, null);
}
private native static boolean htmlImportsSupported()
/*-{
return 'import' in $doc.createElement('link');
}-*/;
/**
* Executes a function after all imports have been loaded and when the
* passed element is ready to use.
* For browsers not supporting html imports, it loads the webcomponentsjs polyfill.
*/
public static native void whenReady(PolymerFunction f, Element e)
/*-{
function registered() {
if (e) {
var id = setInterval(function() {
if (@com.vaadin.polymer.Polymer::isRegisteredElement(*)(e)) {
clearInterval(id);
if (f) f(e);
}
}, 10);
} else {
if (f) f();
}
}
function done() {
$wnd.HTMLImports.whenReady(registered);
}
function loadPolyfill() {
var s = $doc.createElement('script');
s.src = @com.vaadin.polymer.Polymer::absoluteHref(*)
('webcomponentsjs/webcomponents-lite.js');
s.onreadystatechange = s.onload = done;
$doc.head.appendChild(s);
}
if (!$wnd.HTMLImports) {
if (@com.vaadin.polymer.Polymer::hasHtmlImports) {
registered();
} else {
loadPolyfill();
}
} else {
done();
}
}-*/;
/**
* If an element is not ready, loops until it gets ready, then
* run a PolymerFunction (JsFunction or JavaFunction)
* @deprecated use {@link #whenReady(Function, Element)} instead.
*/
@Deprecated
private static void onReady(Element e, Object f) {
whenReady((PolymerFunction)f, e);
}
/**
* Utility method to show a loading element if there is no one in
* hosting page.
*/
public static void startLoading() {
Element l = DOM.getElementById("loading");
if (l == null) {
l = DOM.createDiv();
l.setAttribute("style", "position:fixed;top:0px;left:0px;width:100%;text-align:center;font-family:arial;font-size:24px;color:#4285f4;");
l.setId("loading");
l.setInnerText("loading" + "...");
Document.get().getBody().appendChild(l);
}
}
public static void endLoading(final Element container, Element webcomponent) {
endLoading(container, webcomponent, null);
}
/**
* Utility method to remove a loading message and show a container when a
* web component becomes available.
*
* @param container : The container to show when the component is available
* @param webcomponent : Web component to monitor
* @param func : Calback function
*/
public static void endLoading(final Element container, Element webcomponent, final PolymerFunction func) {
container.getStyle().setOpacity(0);
container.getStyle().setProperty("transition", "opacity 1.1s");
ready(webcomponent, new PolymerFunction() {
public Object call(Object arg) {
reFlow();
container.getStyle().setOpacity(1);
DOM.getElementById("loading").getStyle().setOpacity(0);
return func != null ? func.call(arg) : null;
}
});
}
/**
* Force a browser re-flow. For some reason in Chrome we need to force
* it the very first time we initialize the UI. It seems it happens with
* widgets and no with elements but not 100% positive. To test it try
* to reload the app in SDM and do not move the mouse, moving or clicking
* mouse on body also makes the UI re-draw.
*
*/
private static native void reFlow()
/*-{
if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {
var c = 0;
var id = setInterval(function() {
// Using $doc.body.offsetWidth in an if, otherwise closure
// compiler prunes it.
if (c++ >= 20 && $doc.body.offsetWidth > 0)
clearInterval(id);
}, 50);
}
}-*/;
/**
* Box a native JS array in a Java List. It does not have any performance
* penalty because we directly set the native array of the super ArrayList
* implementation.
*/
public static native <T> List<T> asList(JavaScriptObject o)
/*-{
var l = @java.util.ArrayList::new()();
l.@java.util.ArrayList::array = o;
return l;
}-*/;
/**
* UnBox the native JS array in a Java List. It does not have any performance
* penalty because we directly take the native array of the super ArrayList
* implementation.
*/
public static native <T extends JavaScriptObject> JsArray<T> asJsArray(List<?> l)
/*-{
return l.@java.util.ArrayList::array;
}-*/;
/**
* Utility method for getting a property for a JS object
*/
public native static <T> T property(Object jso, String name)
/*-{
return jso[name] || null;
}-*/;
/**
* Utility method for setting properties to JS objects.
* In case that value is a JSON string it must be based to Polymer attribute setter
* so as it's able to parse. Needed when setting json values in UIBinder.
*/
public native static void property(HTMLElement jso, String name, String value)
/*-{
if (jso.setAttribute && /^[\[\{]/.test(value)) {
jso.setAttribute(name.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase(), value);
} else {
jso[name] = value;
}
}-*/;
/**
* Utility method for setting properties to JS objects.
*/
public native static void property(Object jso, String name, Object value)
/*-{
jso[name] = value;
}-*/;
/**
* Utility method for setting a function to a JS object.
* Useful for binding functions to templates.
*/
public static void function(Object jso, String name, PolymerFunction fnc) {
property(jso, name, fnc);
}
/**
* Utility method for calling a function of a JS object.
*/
public native static <T> T apply(Object jso, String methodName, Object... args)
/*-{
return jso[methodName].apply(jso, args);
}-*/;
/**
* Return the dom API of one element.
*/
public static DomApi dom(Object element) {
return Polymer.dom(element);
}
}