/
vaadin-context-menu.html
636 lines (571 loc) · 21.8 KB
/
vaadin-context-menu.html
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
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
<!--
@license
Copyright (c) 2017 Vaadin Ltd.
This program is available under Apache License Version 2.0, available at https://vaadin.com/license/
-->
<link rel="import" href="../../polymer/polymer-element.html">
<link rel="import" href="../../polymer/lib/mixins/gesture-event-listeners.html">
<link rel="import" href="../../polymer/lib/utils/flattened-nodes-observer.html">
<link rel="import" href="vaadin-contextmenu-event.html">
<link rel="import" href="vaadin-device-detector.html">
<link rel="import" href="vaadin-contextmenu-items-mixin.html">
<link rel="import" href="../../vaadin-element-mixin/vaadin-element-mixin.html">
<link rel="import" href="../../vaadin-themable-mixin/vaadin-theme-property-mixin.html">
<link rel="import" href="vaadin-context-menu-overlay.html">
<dom-module id="vaadin-context-menu">
<template>
<style>
:host {
display: block;
}
:host([hidden]) {
display: none !important;
}
</style>
<slot id="slot"></slot>
<vaadin-device-detector phone="{{_phone}}" touch="{{_touch}}"></vaadin-device-detector>
<vaadin-context-menu-overlay id="overlay"
on-opened-changed="_onOverlayOpened"
on-vaadin-overlay-open="_onVaadinOverlayOpen"
with-backdrop="[[_phone]]"
phone$="[[_phone]]"
model="[[_context]]"
theme$="[[theme]]">
</vaadin-context-menu-overlay>
</template>
<script>
(function() {
/**
*
* `<vaadin-context-menu>` is a Web Component for creating context menus. The content of the
* menu can be populated in three ways: imperatively by using the items API or a renderer callback function and
* declaratively by using Polymer's Templates.
*
* ### Items
*
* Items is a higher level convenience API for defining a (hierarchical) menu structure for the component.
* If a menu item has a non-empty `children` set, a sub-menu with the child items is opened
* next to the parent menu on mouseover, tap or a right arrow keypress.
*
* ```javascript
* contextMenu.items = [
* {text: 'Menu Item 1', children:
* [
* {text: 'Menu Item 1-1', checked: true},
* {text: 'Menu Item 1-2'}
* ]
* },
* {component: 'hr'},
* {text: 'Menu Item 2', children:
* [
* {text: 'Menu Item 2-1'},
* {text: 'Menu Item 2-2', disabled: true}
* ]
* },
* {text: 'Menu Item 3', disabled: true}
* ];
* ```
*
* **NOTE:** when the `items` array is defined, the renderer or a template cannot be used.
*
* ### Rendering
*
* The renderer function provides `root`, `contextMenu`, `model` arguments when applicable.
* Generate DOM content by using `model` object properties if needed, append it to the `root`
* element and control the state of the host element by accessing `contextMenu`. Before generating
* new content, the renderer function should check if there is already content in `root` for reusing it.
*
* ```html
* <vaadin-context-menu id="contextMenu">
* <p>This paragraph has a context menu.</p>
* </vaadin-context-menu>
* ```
* ```js
* const contextMenu = document.querySelector('#contextMenu');
* contextMenu.renderer = (root, contextMenu, context) => {
* let listBox = root.firstElementChild;
* if (!listBox) {
* listBox = document.createElement('vaadin-list-box');
* root.appendChild(listBox);
* }
*
* let item = listBox.querySelector('vaadin-item');
* if (!item) {
* item = document.createElement('vaadin-item');
* listBox.appendChild(item);
* }
* item.textContent = 'Content of the selector: ' + context.target.textContent;
* };
* ```
*
* You can access the menu context inside the renderer using
* `context.target` and `context.detail`.
*
* Renderer is called on the opening of the context-menu and each time the related context is updated.
* DOM generated during the renderer call can be reused
* in the next renderer call and will be provided with the `root` argument.
* On first call it will be empty.
*
* **NOTE:** when the `renderer` function is defined, the template content
* is not in use.
*
* ### Polymer Templates
*
* Alternatively to using the `renderer`, you can populate
* the menu content using Polymer's Templates:
*
* ```html
* <vaadin-context-menu>
* <template>
* <vaadin-list-box>
* <vaadin-item>First menu item</vaadin-item>
* <vaadin-item>Second menu item</vaadin-item>
* </vaadin-list-box>
* </template>
* </vaadin-context-menu>
* ```
*
* ### “vaadin-contextmenu” Gesture Event
*
* `vaadin-contextmenu` is a gesture event (a custom event),
* which is dispatched after either `contextmenu` and long touch events.
* This enables support for both mouse and touch environments in a uniform way.
*
* `<vaadin-context-menu>` opens the menu overlay on the `vaadin-contextmenu`
* event by default.
*
* ### Menu Listener
*
* By default, the `<vaadin-context-menu>` element listens for the menu opening
* event on itself. In order to have a context menu on your content, wrap
* your content with the `<vaadin-context-menu>` element, and add a template
* element with a menu. Example:
*
* ```html
* <vaadin-context-menu>
* <template>
* <vaadin-list-box>
* <vaadin-item>First menu item</vaadin-item>
* <vaadin-item>Second menu item</vaadin-item>
* </vaadin-list-box>
* </template>
*
* <p>This paragraph has the context menu provided in the above template.</p>
* <p>Another paragraph with the context menu.</p>
* </vaadin-context-menu>
* ```
*
* In case if you do not want to wrap the page content, you can listen for
* events on an element outside the `<vaadin-context-menu>` by setting the
* `listenOn` property:
*
* ```html
* <vaadin-context-menu id="customListener">
* <template>
* <vaadin-list-box>
* ...
* </vaadin-list-box>
* </template>
* </vaadin-context-menu>
*
* <div id="menuListener">The element that listens for the context menu.</div>
*
* <script>
* const contextMenu = document.querySelector('vaadin-context-menu#customListener');
* contextMenu.listenOn = document.querySelector('#menuListener');
* </script>
* ```
*
* ### Filtering Menu Targets
*
* By default, the listener element and all its descendants open the context
* menu. You can filter the menu targets to a smaller set of elements inside
* the listener element by setting the `selector` property.
*
* In the following example, only the elements matching `.has-menu` will open the context menu:
*
* ```html
* <vaadin-context-menu selector=".has-menu">
* <template>
* <vaadin-list-box>
* ...
* </vaadin-list-box>
* </template>
*
* <p class="has-menu">This paragraph opens the context menu</p>
* <p>This paragraph does not open the context menu</p>
* </vaadin-context-menu>
* ```
*
* ### Menu Context
*
* You can bind to the following properties in the menu template:
*
* - `target` is the menu opening event target, which is the element that
* the user has called the context menu for
* - `detail` is the menu opening event detail
*
* In the following example, the menu item text is composed with the contents
* of the element that opened the menu:
*
* ```html
* <vaadin-context-menu selector="li">
* <template>
* <vaadin-list-box>
* <vaadin-item>The menu target: [[target.textContent]]</vaadin-item>
* </vaadin-list-box>
* </template>
*
* <ul>
* <li>Foo</li>
* <li>Bar</li>
* <li>Baz</li>
* </ul>
* </vaadin-context-menu>
* ```
*
* ### Styling
*
* `<vaadin-context-menu>` uses `<vaadin-context-menu-overlay>` internal
* themable component as the actual visible context menu overlay. See
* See [`<vaadin-overlay>` documentation](https://github.com/vaadin/vaadin-overlay/blob/master/src/vaadin-overlay.html)
* for `<vaadin-context-menu-overlay>` parts.
*
* See [ThemableMixin – how to apply styles for shadow parts](https://github.com/vaadin/vaadin-themable-mixin/wiki)
*
* Note: the `theme` attribute value set on `<vaadin-context-menu>` is
* propagated to the internal `<vaadin-context-menu-overlay>` component.
*
* @memberof Vaadin
* @mixes Vaadin.ElementMixin
* @mixes Vaadin.ThemePropertyMixin
* @mixes Vaadin.ContextMenu.ItemsMixin
* @mixes Polymer.GestureEventListeners
* @demo demo/index.html
*/
class ContextMenuElement extends
Vaadin.ElementMixin(
Vaadin.ThemePropertyMixin(
Vaadin.ContextMenu.ItemsMixin(
Polymer.GestureEventListeners(Polymer.Element)))) {
static get is() {
return 'vaadin-context-menu';
}
static get version() {
return '4.3.0-alpha1';
}
static get properties() {
return {
/**
* CSS selector that can be used to target any child element
* of the context menu to listen for `openOn` events.
*/
selector: {
type: String
},
/**
* True if the overlay is currently displayed.
*/
opened: {
type: Boolean,
value: false,
notify: true,
readOnly: true
},
/**
* Event name to listen for opening the context menu.
*/
openOn: {
type: String,
value: 'vaadin-contextmenu'
},
/**
* The target element that's listened to for context menu opening events.
* By default the vaadin-context-menu listens to the target's `vaadin-contextmenu`
* events.
* @type {HTMLElement}
* @default self
*/
listenOn: {
type: Object,
value: function() {
return this;
}
},
/**
* Event name to listen for closing the context menu.
*/
closeOn: {
type: String,
value: 'click',
observer: '_closeOnChanged'
},
/**
* Custom function for rendering the content of the menu overlay.
* Receives three arguments:
*
* - `root` The root container DOM element. Append your content to it.
* - `contextMenu` The reference to the `<vaadin-context-menu>` element.
* - `context` The object with the menu context, contains:
* - `context.target` the target of the menu opening event,
* - `context.detail` the menu opening event detail.
*/
renderer: {
type: Function
},
_context: Object,
_boundClose: Object,
_boundOpen: Object,
_contentTemplate: Object,
_oldTemplate: Object,
_oldRenderer: Object,
_touch: Boolean
};
}
static get observers() {
return [
'_openedChanged(opened)',
'_contextChanged(_context, _instance)',
'_targetOrOpenOnChanged(listenOn, openOn)',
'_templateOrRendererChanged(_contentTemplate, renderer, _context, items)'
];
}
constructor() {
super();
this._boundOpen = this.open.bind(this);
this._boundClose = this.close.bind(this);
this._boundOnGlobalContextMenu = this._onGlobalContextMenu.bind(this);
}
ready() {
super.ready();
this._observer = new Polymer.FlattenedNodesObserver(this, info => {
this._setTemplateFromNodes(info.addedNodes);
});
}
_setTemplateFromNodes(nodes) {
this._contentTemplate = nodes.filter(node => node.localName && node.localName === 'template')[0] || this._contentTemplate;
}
// Runs before overlay is fully rendered
_onOverlayOpened(e) {
this._setOpened(e.detail.value);
}
// Runs after overlay is fully rendered
_onVaadinOverlayOpen(e) {
this.__alignOverlayPosition();
this.$.overlay.style.opacity = '';
const child = this.$.overlay.content.querySelector(':not(style):not(slot)');
if (child) {
child.focus();
}
}
_targetOrOpenOnChanged(listenOn, openOn) {
if (this._oldListenOn && this._oldOpenOn) {
this._unlisten(this._oldListenOn, this._oldOpenOn, this._boundOpen);
this._oldListenOn.style.webkitTouchCallout = '';
this._oldListenOn.style.webkitUserSelect = '';
this._oldListenOn = null;
this._oldOpenOn = null;
}
if (listenOn && openOn) {
this._listen(listenOn, openOn, this._boundOpen);
// note: these styles don't seem to work in Firefox on iOS.
listenOn.style.webkitTouchCallout = 'none';
listenOn.style.webkitUserSelect = 'none';
this._oldListenOn = listenOn;
this._oldOpenOn = openOn;
}
}
_closeOnChanged(closeOn, oldCloseOn) {
// Listen on this.$.overlay.root to workaround issue on
// ShadyDOM polyfill: https://github.com/webcomponents/shadydom/issues/159
// Outside click event from overlay
const evtOverlay = 'vaadin-overlay-outside-click';
if (oldCloseOn) {
this._unlisten(this.$.overlay, oldCloseOn, this._boundClose);
this._unlisten(this.$.overlay.root, oldCloseOn, this._boundClose);
}
if (closeOn) {
this._listen(this.$.overlay, closeOn, this._boundClose);
this._listen(this.$.overlay.root, closeOn, this._boundClose);
this._unlisten(this.$.overlay, evtOverlay, this._preventDefault);
} else {
this._listen(this.$.overlay, evtOverlay, this._preventDefault);
}
}
_preventDefault(e) {
e.preventDefault();
}
_openedChanged(opened) {
if (opened) {
if (!this._instance) {
this.$.overlay.template = this.querySelector('template');
this._instance = this.$.overlay._instance;
}
document.documentElement.addEventListener('contextmenu', this._boundOnGlobalContextMenu, true);
} else {
document.documentElement.removeEventListener('contextmenu', this._boundOnGlobalContextMenu, true);
}
// Has to be set after instance has been created
this.$.overlay.opened = opened;
}
/**
* Manually invoke existing renderer.
*/
render() {
this.$.overlay.render();
}
_removeNewRendererOrTemplate(template, oldTemplate, renderer, oldRenderer) {
if (template !== oldTemplate) {
this._contentTemplate = undefined;
} else if (renderer !== oldRenderer) {
this.renderer = undefined;
}
}
_templateOrRendererChanged(template, renderer, context, items) {
if (template && renderer) {
this._removeNewRendererOrTemplate(template, this._oldTemplate, renderer, this._oldRenderer);
throw new Error('You should only use either a renderer or a template for context-menu content');
}
this._oldTemplate = template;
this._oldRenderer = renderer;
if (items) {
if (template || renderer) {
throw new Error('The items API cannot be used together with a template/renderer');
}
if (this.closeOn === 'click') {
this.closeOn = '';
}
renderer = this.__itemsRenderer;
}
if (renderer && context) {
this.$.overlay.setProperties({owner: this, renderer: renderer});
}
}
_contextChanged(context, instance) {
if (context === undefined || instance === undefined) {
return;
}
instance.detail = context.detail;
instance.target = context.target;
}
/**
* Closes the overlay.
*/
close() {
this._setOpened(false);
}
_contextTarget(e) {
if (this.selector) {
const targets = this.listenOn.querySelectorAll(this.selector);
return Array.prototype.filter.call(targets, el => {
return e.composedPath().indexOf(el) > -1;
})[0];
} else {
return e.target;
}
}
/**
* Opens the overlay.
* @param {Event} e used as the context for the menu. Overlay coordinates are taken from this event.
*/
open(e) {
if (e && !this.opened) {
this._context = {
detail: e.detail,
target: this._contextTarget(e)
};
if (this._context.target) {
this._preventDefault(e);
e.stopPropagation();
// Used in alignment which is delayed until overlay is rendered
this.__x = this._getEventCoordinate(e, 'x');
this.__y = this._getEventCoordinate(e, 'y');
this.$.overlay.style.opacity = '0';
this._setOpened(true);
}
}
}
__alignOverlayPosition() {
const overlay = this.$.overlay;
const style = overlay.style;
// Reset all properties before measuring
['top', 'right', 'bottom', 'left'].forEach(prop => style.removeProperty(prop));
['right-aligned', 'bottom-aligned'].forEach(attr => overlay.removeAttribute(attr));
// Measure actual overlay and content sizes
const overlayRect = overlay.getBoundingClientRect();
const contentRect = overlay.$.overlay.getBoundingClientRect();
// Maximum x and y values are imposed by content size and overlay limits.
const xMax = overlayRect.right - contentRect.width;
const yMax = overlayRect.bottom - contentRect.height;
// Reuse saved x and y event values, in order to this method be used async
// in the `vaadin-overlay-change` which guarantees that overlay is ready
const x = this.__x || overlayRect.left;
const y = this.__y || overlayRect.top;
// Select one overlay corner and move to the event x/y position.
// Then set styling attrs for flex-aligning the content appropriatelly.
const wdthVport = document.documentElement.clientWidth;
const hghtVport = document.documentElement.clientHeight;
if (x < wdthVport / 2 || x < xMax) {
style.left = x + 'px';
} else {
style.right = Math.max(0, (wdthVport - x)) + 'px';
overlay.setAttribute('right-aligned', '');
}
if (y < hghtVport / 2 || y < yMax) {
style.top = y + 'px';
} else {
style.bottom = Math.max(0, (hghtVport - y)) + 'px';
overlay.setAttribute('bottom-aligned', '');
}
}
_getEventCoordinate(event, coord) {
if (event.detail instanceof Object) {
if (event.detail[coord]) {
// Polymer gesture events, get coordinate from detail
return event.detail[coord];
} else if (event.detail.sourceEvent) {
// Unwrap detailed event
return this._getEventCoordinate(event.detail.sourceEvent, coord);
}
} else {
// Native mouse or touch event
const prop = 'client' + coord.toUpperCase();
return event.changedTouches ? event.changedTouches[0][prop] : event[prop];
}
}
_listen(node, evType, handler) {
if (Polymer.Gestures.gestures[evType]) {
Polymer.Gestures.addListener(node, evType, handler);
} else {
node.addEventListener(evType, handler);
}
}
_unlisten(node, evType, handler) {
if (Polymer.Gestures.gestures[evType]) {
Polymer.Gestures.removeListener(node, evType, handler);
} else {
node.removeEventListener(evType, handler);
}
}
_onGlobalContextMenu(e) {
if (!e.shiftKey) {
e.preventDefault();
this.close();
}
}
/**
* Fired when an item is selected when the context menu is populated using the `items` API.
*
* @event item-selected
* @param {Object} detail
* @param {Object} detail.value the selected menu item
*/
}
customElements.define(ContextMenuElement.is, ContextMenuElement);
/**
* @namespace Vaadin
*/
window.Vaadin.ContextMenuElement = ContextMenuElement;
})();
</script>
</dom-module>