]> git.proxmox.com Git - proxmox-widget-toolkit.git/blob - src/Toolkit.js
Toolkit: remove pie chart fix
[proxmox-widget-toolkit.git] / src / Toolkit.js
1 // ExtJS related things
2
3 // do not send '_dc' parameter
4 Ext.Ajax.disableCaching = false;
5
6 // custom Vtypes
7 Ext.apply(Ext.form.field.VTypes, {
8 IPAddress: function(v) {
9 return Proxmox.Utils.IP4_match.test(v);
10 },
11 IPAddressText: gettext('Example') + ': 192.168.1.1',
12 IPAddressMask: /[\d.]/i,
13
14 IPCIDRAddress: function(v) {
15 let result = Proxmox.Utils.IP4_cidr_match.exec(v);
16 // limits according to JSON Schema see
17 // pve-common/src/PVE/JSONSchema.pm
18 return result !== null && result[1] >= 8 && result[1] <= 32;
19 },
20 IPCIDRAddressText: gettext('Example') + ': 192.168.1.1/24<br>' + gettext('Valid CIDR Range') + ': 8-32',
21 IPCIDRAddressMask: /[\d./]/i,
22
23 IP6Address: function(v) {
24 return Proxmox.Utils.IP6_match.test(v);
25 },
26 IP6AddressText: gettext('Example') + ': 2001:DB8::42',
27 IP6AddressMask: /[A-Fa-f0-9:]/,
28
29 IP6CIDRAddress: function(v) {
30 let result = Proxmox.Utils.IP6_cidr_match.exec(v);
31 // limits according to JSON Schema see
32 // pve-common/src/PVE/JSONSchema.pm
33 return result !== null && result[1] >= 8 && result[1] <= 128;
34 },
35 IP6CIDRAddressText: gettext('Example') + ': 2001:DB8::42/64<br>' + gettext('Valid CIDR Range') + ': 8-128',
36 IP6CIDRAddressMask: /[A-Fa-f0-9:/]/,
37
38 IP6PrefixLength: function(v) {
39 return v >= 0 && v <= 128;
40 },
41 IP6PrefixLengthText: gettext('Example') + ': X, where 0 <= X <= 128',
42 IP6PrefixLengthMask: /[0-9]/,
43
44 IP64Address: function(v) {
45 return Proxmox.Utils.IP64_match.test(v);
46 },
47 IP64AddressText: gettext('Example') + ': 192.168.1.1 2001:DB8::42',
48 IP64AddressMask: /[A-Fa-f0-9.:]/,
49
50 IP64CIDRAddress: function(v) {
51 let result = Proxmox.Utils.IP64_cidr_match.exec(v);
52 if (result === null) {
53 return false;
54 }
55 if (result[1] !== undefined) {
56 return result[1] >= 8 && result[1] <= 128;
57 } else if (result[2] !== undefined) {
58 return result[2] >= 8 && result[2] <= 32;
59 } else {
60 return false;
61 }
62 },
63 IP64CIDRAddressText: gettext('Example') + ': 192.168.1.1/24 2001:DB8::42/64',
64 IP64CIDRAddressMask: /[A-Fa-f0-9.:/]/,
65
66 MacAddress: function(v) {
67 return (/^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$/).test(v);
68 },
69 MacAddressMask: /[a-fA-F0-9:]/,
70 MacAddressText: gettext('Example') + ': 01:23:45:67:89:ab',
71
72 MacPrefix: function(v) {
73 return (/^[a-f0-9][02468ace](?::[a-f0-9]{2}){0,2}:?$/i).test(v);
74 },
75 MacPrefixMask: /[a-fA-F0-9:]/,
76 MacPrefixText: gettext('Example') + ': 02:8f - ' + gettext('only unicast addresses are allowed'),
77
78 BridgeName: function(v) {
79 return (/^vmbr\d{1,4}$/).test(v);
80 },
81 VlanName: function(v) {
82 if (Proxmox.Utils.VlanInterface_match.test(v)) {
83 return true;
84 } else if (Proxmox.Utils.Vlan_match.test(v)) {
85 return true;
86 }
87 return true;
88 },
89 BridgeNameText: gettext('Format') + ': vmbr<b>N</b>, where 0 <= <b>N</b> <= 9999',
90
91 BondName: function(v) {
92 return (/^bond\d{1,4}$/).test(v);
93 },
94 BondNameText: gettext('Format') + ': bond<b>N</b>, where 0 <= <b>N</b> <= 9999',
95
96 InterfaceName: function(v) {
97 return (/^[a-z][a-z0-9_]{1,20}$/).test(v);
98 },
99 InterfaceNameText: gettext("Allowed characters") + ": 'a-z', '0-9', '_'<br />" +
100 gettext("Minimum characters") + ": 2<br />" +
101 gettext("Maximum characters") + ": 21<br />" +
102 gettext("Must start with") + ": 'a-z'",
103
104 StorageId: function(v) {
105 return (/^[a-z][a-z0-9\-_.]*[a-z0-9]$/i).test(v);
106 },
107 StorageIdText: gettext("Allowed characters") + ": 'A-Z', 'a-z', '0-9', '-', '_', '.'<br />" +
108 gettext("Minimum characters") + ": 2<br />" +
109 gettext("Must start with") + ": 'A-Z', 'a-z'<br />" +
110 gettext("Must end with") + ": 'A-Z', 'a-z', '0-9'<br />",
111
112 ConfigId: function(v) {
113 return (/^[a-z][a-z0-9_]+$/i).test(v);
114 },
115 ConfigIdText: gettext("Allowed characters") + ": 'A-Z', 'a-z', '0-9', '_'<br />" +
116 gettext("Minimum characters") + ": 2<br />" +
117 gettext("Must start with") + ": " + gettext("letter"),
118
119 HttpProxy: function(v) {
120 return (/^http:\/\/.*$/).test(v);
121 },
122 HttpProxyText: gettext('Example') + ": http://username:password&#64;host:port/",
123
124 DnsName: function(v) {
125 return Proxmox.Utils.DnsName_match.test(v);
126 },
127 DnsNameText: gettext('This is not a valid DNS name'),
128
129 // workaround for https://www.sencha.com/forum/showthread.php?302150
130 proxmoxMail: function(v) {
131 return (/^(\w+)([-+.][\w]+)*@(\w[-\w]*\.){1,5}([A-Za-z]){2,63}$/).test(v);
132 },
133 proxmoxMailText: gettext('Example') + ": user@example.com",
134
135 DnsOrIp: function(v) {
136 if (!Proxmox.Utils.DnsName_match.test(v) &&
137 !Proxmox.Utils.IP64_match.test(v)) {
138 return false;
139 }
140
141 return true;
142 },
143 DnsOrIpText: gettext('Not a valid DNS name or IP address.'),
144
145 HostPort: function(v) {
146 return Proxmox.Utils.HostPort_match.test(v) ||
147 Proxmox.Utils.HostPortBrackets_match.test(v) ||
148 Proxmox.Utils.IP6_dotnotation_match.test(v);
149 },
150 HostPortText: gettext('Host/IP address or optional port is invalid'),
151
152 HostList: function(v) {
153 let list = v.split(/[ ,;]+/);
154 let i;
155 for (i = 0; i < list.length; i++) {
156 if (list[i] === '') {
157 continue;
158 }
159
160 if (!Proxmox.Utils.HostPort_match.test(list[i]) &&
161 !Proxmox.Utils.HostPortBrackets_match.test(list[i]) &&
162 !Proxmox.Utils.IP6_dotnotation_match.test(list[i])) {
163 return false;
164 }
165 }
166
167 return true;
168 },
169 HostListText: gettext('Not a valid list of hosts'),
170
171 password: function(val, field) {
172 if (field.initialPassField) {
173 let pwd = field.up('form').down(`[name=${field.initialPassField}]`);
174 return val === pwd.getValue();
175 }
176 return true;
177 },
178
179 passwordText: gettext('Passwords do not match'),
180
181 email: function(value) {
182 let emailre = /^[\w+~-]+(\.[\w+~-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*$/;
183 return emailre.test(value);
184 },
185 });
186
187 // we always want the number in x.y format and never in, e.g., x,y
188 Ext.define('PVE.form.field.Number', {
189 override: 'Ext.form.field.Number',
190 submitLocaleSeparator: false,
191 });
192
193 // ExtJs 5-6 has an issue with caching
194 // see https://www.sencha.com/forum/showthread.php?308989
195 Ext.define('Proxmox.UnderlayPool', {
196 override: 'Ext.dom.UnderlayPool',
197
198 checkOut: function() {
199 let cache = this.cache,
200 len = cache.length,
201 el;
202
203 // do cleanup because some of the objects might have been destroyed
204 while (len--) {
205 if (cache[len].destroyed) {
206 cache.splice(len, 1);
207 }
208 }
209 // end do cleanup
210
211 el = cache.shift();
212
213 if (!el) {
214 el = Ext.Element.create(this.elementConfig);
215 el.setVisibilityMode(2);
216 //<debug>
217 // tell the spec runner to ignore this element when checking if the dom is clean
218 el.dom.setAttribute('data-sticky', true);
219 //</debug>
220 }
221
222 return el;
223 },
224 });
225
226 // 'Enter' in Textareas and aria multiline fields should not activate the
227 // defaultbutton, fixed in extjs 6.0.2
228 Ext.define('PVE.panel.Panel', {
229 override: 'Ext.panel.Panel',
230
231 fireDefaultButton: function(e) {
232 if (e.target.getAttribute('aria-multiline') === 'true' ||
233 e.target.tagName === "TEXTAREA") {
234 return true;
235 }
236 return this.callParent(arguments);
237 },
238 });
239
240 // if the order of the values are not the same in originalValue and value
241 // extjs will not overwrite value, but marks the field dirty and thus
242 // the reset button will be enabled (but clicking it changes nothing)
243 // so if the arrays are not the same after resetting, we
244 // clear and set it
245 Ext.define('Proxmox.form.ComboBox', {
246 override: 'Ext.form.field.ComboBox',
247
248 reset: function() {
249 // copied from combobox
250 let me = this;
251 me.callParent();
252
253 // clear and set when not the same
254 let value = me.getValue();
255 if (Ext.isArray(me.originalValue) && Ext.isArray(value) &&
256 !Ext.Array.equals(value, me.originalValue)) {
257 me.clearValue();
258 me.setValue(me.originalValue);
259 }
260 },
261
262 // we also want to open the trigger on editable comboboxes by default
263 initComponent: function() {
264 let me = this;
265 me.callParent();
266
267 if (me.editable) {
268 // The trigger.picker causes first a focus event on the field then
269 // toggles the selection picker. Thus skip expanding in this case,
270 // else our focus listener expands and the picker.trigger then
271 // collapses it directly afterwards.
272 Ext.override(me.triggers.picker, {
273 onMouseDown: function(e) {
274 // copied "should we focus" check from Ext.form.trigger.Trigger
275 if (e.pointerType !== 'touch' && !this.field.owns(Ext.Element.getActiveElement())) {
276 me.skip_expand_on_focus = true;
277 }
278 this.callParent(arguments);
279 },
280 });
281
282 me.on("focus", function(combobox) {
283 if (!combobox.isExpanded && !combobox.skip_expand_on_focus) {
284 combobox.expand();
285 }
286 combobox.skip_expand_on_focus = false;
287 });
288 }
289 },
290 });
291
292 // when refreshing a grid/tree view, restoring the focus moves the view back to
293 // the previously focused item. Save scroll position before refocusing.
294 Ext.define(null, {
295 override: 'Ext.view.Table',
296
297 jumpToFocus: false,
298
299 saveFocusState: function() {
300 var me = this,
301 store = me.dataSource,
302 actionableMode = me.actionableMode,
303 navModel = me.getNavigationModel(),
304 focusPosition = actionableMode ? me.actionPosition : navModel.getPosition(true),
305 activeElement = Ext.fly(Ext.Element.getActiveElement()),
306 focusCell = focusPosition && focusPosition.view === me &&
307 Ext.fly(focusPosition.getCell(true)),
308 refocusRow, refocusCol, record;
309
310 // The navModel may return a position that is in a locked partner, so check that
311 // the focusPosition's cell contains the focus before going forward.
312 // The skipSaveFocusState is set by Actionables which actively control
313 // focus destination. See CellEditing#activateCell.
314 if (!me.skipSaveFocusState && focusCell && focusCell.contains(activeElement)) {
315 // Separate this from the instance that the nav model is using.
316 focusPosition = focusPosition.clone();
317
318 // While we deactivate the focused element, suspend focus processing on it.
319 activeElement.suspendFocusEvents();
320
321 // Suspend actionable mode.
322 // Each Actionable must silently save its state ready to resume when focus
323 // can be restored but should only do that if the activeElement is not the cell itself,
324 // this happens when the grid is refreshed while one of the actionables is being
325 // deactivated (e.g. Calling view refresh inside CellEditor 'edit' event listener).
326 if (actionableMode && focusCell.dom !== activeElement.dom) {
327 me.suspendActionableMode();
328 } else {
329 // Clear position, otherwise the setPosition on the other side
330 // will be rejected as a no-op if the resumption position is logically
331 // equivalent.
332 actionableMode = false;
333 navModel.setPosition();
334 }
335
336 // Do not leave the element in tht state in case refresh fails, and restoration
337 // closure not called.
338 activeElement.resumeFocusEvents();
339
340 // if the store is expanding or collapsing, we should never scroll the view.
341 if (store.isExpandingOrCollapsing) {
342 return Ext.emptyFn;
343 }
344
345 // The following function will attempt to refocus back in the same mode to the same cell
346 // as it was at before based upon the previous record (if it's still in the store),
347 // or the row index.
348 return function() {
349 var all;
350
351 // May have changed due to reconfigure
352 store = me.dataSource;
353
354 // If we still have data, attempt to refocus in the same mode.
355 if (store.getCount()) {
356 all = me.all;
357
358 // Adjust expectations of where we are able to refocus according to
359 // what kind of destruction might have been wrought on this view's DOM
360 // during focus save.
361 refocusRow =
362 Math.min(Math.max(focusPosition.rowIdx, all.startIndex), all.endIndex);
363
364 refocusCol = Math.min(
365 focusPosition.colIdx,
366 me.getVisibleColumnManager().getColumns().length - 1,
367 );
368
369 record = focusPosition.record;
370
371 focusPosition = new Ext.grid.CellContext(me).setPosition(
372 record && store.contains(record) && !record.isCollapsedPlaceholder
373 ? record
374 : refocusRow,
375 refocusCol,
376 );
377
378 // Maybe there are no cells. eg: all groups collapsed.
379 if (focusPosition.getCell(true)) {
380 if (actionableMode) {
381 me.resumeActionableMode(focusPosition);
382 } else {
383 // we sometimes want to scroll back to where we are
384
385 let x = me.getScrollX();
386 let y = me.getScrollY();
387
388 // Pass "preventNavigation" as true
389 // so that that does not cause selection.
390 navModel.setPosition(focusPosition, null, null, null, true);
391
392 if (!navModel.getPosition()) {
393 focusPosition.column.focus();
394 }
395
396 if (!me.jumpToFocus) {
397 me.scrollTo(x, y);
398 }
399 }
400 }
401 } else { // No rows - focus associated column header
402 focusPosition.column.focus();
403 }
404 };
405 }
406 return Ext.emptyFn;
407 },
408 });
409
410 // should be fixed with ExtJS 6.0.2, see:
411 // https://www.sencha.com/forum/showthread.php?307244-Bug-with-datefield-in-window-with-scroll
412 Ext.define('Proxmox.Datepicker', {
413 override: 'Ext.picker.Date',
414 hideMode: 'visibility',
415 });
416
417 // ExtJS 6.0.1 has no setSubmitValue() (although you find it in the docs).
418 // Note: this.submitValue is a boolean flag, whereas getSubmitValue() returns
419 // data to be submitted.
420 Ext.define('Proxmox.form.field.Text', {
421 override: 'Ext.form.field.Text',
422
423 setSubmitValue: function(v) {
424 this.submitValue = v;
425 },
426 });
427
428 // make mousescrolling work in firefox in the containers overflowhandler,
429 // by using only the 'wheel' event not 'mousewheel'(fixed in 7.3)
430 // also reverse the scrolldirection (fixed in 7.3)
431 // and reduce the default increment
432 Ext.define(null, {
433 override: 'Ext.layout.container.boxOverflow.Scroller',
434
435 wheelIncrement: 1,
436
437 getWheelDelta: function(e) {
438 return -e.getWheelDelta(e);
439 },
440
441 onOwnerRender: function(owner) {
442 var me = this,
443 scrollable = {
444 isBoxOverflowScroller: true,
445 x: false,
446 y: false,
447 listeners: {
448 scrollend: this.onScrollEnd,
449 scope: this,
450 },
451 };
452
453 // If no obstrusive scrollbars, allow natural scrolling on mobile touch devices
454 if (!Ext.scrollbar.width() && !Ext.platformTags.desktop) {
455 scrollable[owner.layout.horizontal ? 'x' : 'y'] = true;
456 } else {
457 me.wheelListener = me.layout.innerCt.on(
458 'wheel', me.onMouseWheel, me, { destroyable: true },
459 );
460 }
461
462 owner.setScrollable(scrollable);
463 },
464 });
465
466 // extj 6.7 reversed mousewheel direction... (fixed in 7.3)
467 // https://forum.sencha.com/forum/showthread.php?472517-Mousewheel-scroll-direction-in-numberfield-with-spinners
468 // alse use the 'wheel' event instead of 'mousewheel' (fixed in 7.3)
469 Ext.define('Proxmox.form.field.Spinner', {
470 override: 'Ext.form.field.Spinner',
471
472 onRender: function() {
473 var me = this,
474 spinnerTrigger = me.getTrigger('spinner');
475
476 me.callParent();
477
478 // Init up/down arrow keys
479 if (me.keyNavEnabled) {
480 me.spinnerKeyNav = new Ext.util.KeyNav({
481 target: me.inputEl,
482 scope: me,
483 up: me.spinUp,
484 down: me.spinDown,
485 });
486
487 me.inputEl.on({
488 keyup: me.onInputElKeyUp,
489 scope: me,
490 });
491 }
492
493 // Init mouse wheel
494 if (me.mouseWheelEnabled) {
495 me.mon(me.bodyEl, 'wheel', me.onMouseWheel, me);
496 }
497
498 // in v4 spinUpEl/spinDownEl were childEls, now they are children of the trigger.
499 // create references for compatibility
500 me.spinUpEl = spinnerTrigger.upEl;
501 me.spinDownEl = spinnerTrigger.downEl;
502 },
503
504 onMouseWheel: function(e) {
505 var me = this,
506 delta;
507 if (me.hasFocus) {
508 delta = e.getWheelDelta();
509 if (delta > 0) {
510 me.spinDown();
511 } else if (delta < 0) {
512 me.spinUp();
513 }
514 e.stopEvent();
515 me.onSpinEnd();
516 }
517 },
518 });
519
520 // add '@' to the valid id
521 Ext.define('Proxmox.validIdReOverride', {
522 override: 'Ext.Component',
523 validIdRe: /^[a-z_][a-z0-9\-_@]*$/i,
524 });
525
526 Ext.define('Proxmox.selection.CheckboxModel', {
527 override: 'Ext.selection.CheckboxModel',
528
529 // [P] use whole checkbox cell to multiselect, not only the checkbox
530 checkSelector: '.x-grid-cell-row-checker',
531
532 // TODO: remove all optimizations below to an override for parent 'Ext.selection.Model' ??
533
534 // [ P: optimized to remove all records at once as single remove is O(n^3) slow ]
535 // records can be an index, a record or an array of records
536 doDeselect: function(records, suppressEvent) {
537 var me = this,
538 selected = me.selected,
539 i = 0,
540 len, record,
541 commit;
542 if (me.locked || !me.store) {
543 return false;
544 }
545 if (typeof records === "number") {
546 // No matching record, jump out
547 record = me.store.getAt(records);
548 if (!record) {
549 return false;
550 }
551 records = [
552 record,
553 ];
554 } else if (!Ext.isArray(records)) {
555 records = [
556 records,
557 ];
558 }
559 // [P] a beforedeselection, triggered by me.onSelectChange below, can block removal by
560 // returning false, thus the original implementation removed only here in the commit fn,
561 // which has an abysmal performance O(n^3). As blocking removal is not the norm, go do the
562 // reverse, record blocked records and remove them from the to-be-removed array before
563 // applying it. A FF86 i9-9900K on 10k records goes from >40s to ~33ms for >90% deselection
564 let committed = false;
565 commit = function() {
566 committed = true;
567 if (record === me.selectionStart) {
568 me.selectionStart = null;
569 }
570 };
571 let removalBlocked = [];
572 len = records.length;
573 me.suspendChanges();
574 for (; i < len; i++) {
575 record = records[i];
576 if (me.isSelected(record)) {
577 committed = false;
578 me.onSelectChange(record, false, suppressEvent, commit);
579 if (!committed) {
580 removalBlocked.push(record);
581 }
582 if (me.destroyed) {
583 return false;
584 }
585 }
586 }
587 if (removalBlocked.length > 0) {
588 records.remove(removalBlocked);
589 }
590 selected.remove(records); // [P] FAST(er)
591 me.lastSelected = selected.last();
592 me.resumeChanges();
593 // fire selchange if there was a change and there is no suppressEvent flag
594 me.maybeFireSelectionChange(records.length > 0 && !suppressEvent);
595 return records.length;
596 },
597
598
599 doMultiSelect: function(records, keepExisting, suppressEvent) {
600 var me = this,
601 selected = me.selected,
602 change = false,
603 result, i, len, record, commit;
604
605 if (me.locked) {
606 return;
607 }
608
609 records = !Ext.isArray(records) ? [records] : records;
610 len = records.length;
611 if (!keepExisting && selected.getCount() > 0) {
612 result = me.deselectDuringSelect(records, suppressEvent);
613 if (me.destroyed) {
614 return;
615 }
616 if (result[0]) {
617 // We had a failure during selection, so jump out
618 // Fire selection change if we did deselect anything
619 me.maybeFireSelectionChange(result[1] > 0 && !suppressEvent);
620 return;
621 } else {
622 // Means something has been deselected, so we've had a change
623 change = result[1] > 0;
624 }
625 }
626
627 let gotBlocked, blockedRecords = [];
628 commit = function() {
629 if (!selected.getCount()) {
630 me.selectionStart = record;
631 }
632 gotBlocked = false;
633 change = true;
634 };
635
636 for (i = 0; i < len; i++) {
637 record = records[i];
638 if (me.isSelected(record)) {
639 continue;
640 }
641
642 gotBlocked = true;
643 me.onSelectChange(record, true, suppressEvent, commit);
644 if (me.destroyed) {
645 return;
646 }
647 if (gotBlocked) {
648 blockedRecords.push(record);
649 }
650 }
651 if (blockedRecords.length > 0) {
652 records.remove(blockedRecords);
653 }
654 selected.add(records);
655 me.lastSelected = record;
656
657 // fire selchange if there was a change and there is no suppressEvent flag
658 me.maybeFireSelectionChange(change && !suppressEvent);
659 },
660 deselectDuringSelect: function(toSelect, suppressEvent) {
661 var me = this,
662 selected = me.selected.getRange(),
663 changed = 0,
664 failed = false;
665 // Prevent selection change events from firing, will happen during select
666 me.suspendChanges();
667 me.deselectingDuringSelect = true;
668 let toDeselect = selected.filter(item => !Ext.Array.contains(toSelect, item));
669 if (toDeselect.length > 0) {
670 changed = me.doDeselect(toDeselect, suppressEvent);
671 if (!changed) {
672 failed = true;
673 }
674 if (me.destroyed) {
675 failed = true;
676 changed = 0;
677 }
678 }
679 me.deselectingDuringSelect = false;
680 me.resumeChanges();
681 return [
682 failed,
683 changed,
684 ];
685 },
686 });
687
688 // override the download server url globally, for privacy reasons
689 Ext.draw.Container.prototype.defaultDownloadServerUrl = "-";
690
691 // stop nulling of properties
692 Ext.define('Proxmox.Component', {
693 override: 'Ext.Component',
694 clearPropertiesOnDestroy: false,
695 });
696
697 // force alert boxes to be rendered with an Error Icon
698 // since Ext.Msg is an object and not a prototype, we need to override it
699 // after the framework has been initiated
700 Ext.onReady(function() {
701 Ext.override(Ext.Msg, {
702 alert: function(title, message, fn, scope) { // eslint-disable-line consistent-return
703 if (Ext.isString(title)) {
704 let config = {
705 title: title,
706 message: message,
707 icon: this.ERROR,
708 buttons: this.OK,
709 fn: fn,
710 scope: scope,
711 minWidth: this.minWidth,
712 };
713 return this.show(config);
714 }
715 },
716 });
717 });
718 Ext.define('Ext.ux.IFrame', {
719 extend: 'Ext.Component',
720
721 alias: 'widget.uxiframe',
722
723 loadMask: 'Loading...',
724
725 src: 'about:blank',
726
727 renderTpl: [
728 '<iframe src="{src}" id="{id}-iframeEl" data-ref="iframeEl" name="{frameName}" width="100%" height="100%" frameborder="0" allowfullscreen="true"></iframe>',
729 ],
730 childEls: ['iframeEl'],
731
732 initComponent: function() {
733 this.callParent();
734
735 this.frameName = this.frameName || this.id + '-frame';
736 },
737
738 initEvents: function() {
739 let me = this;
740 me.callParent();
741 me.iframeEl.on('load', me.onLoad, me);
742 },
743
744 initRenderData: function() {
745 return Ext.apply(this.callParent(), {
746 src: this.src,
747 frameName: this.frameName,
748 });
749 },
750
751 getBody: function() {
752 let doc = this.getDoc();
753 return doc.body || doc.documentElement;
754 },
755
756 getDoc: function() {
757 try {
758 return this.getWin().document;
759 } catch (ex) {
760 return null;
761 }
762 },
763
764 getWin: function() {
765 let me = this,
766 name = me.frameName,
767 win = Ext.isIE
768 ? me.iframeEl.dom.contentWindow
769 : window.frames[name];
770 return win;
771 },
772
773 getFrame: function() {
774 let me = this;
775 return me.iframeEl.dom;
776 },
777
778 beforeDestroy: function() {
779 this.cleanupListeners(true);
780 this.callParent();
781 },
782
783 cleanupListeners: function(destroying) {
784 let doc, prop;
785
786 if (this.rendered) {
787 try {
788 doc = this.getDoc();
789 if (doc) {
790 Ext.get(doc).un(this._docListeners);
791 if (destroying && doc.hasOwnProperty) {
792 for (prop in doc) {
793 if (Object.prototype.hasOwnProperty.call(doc, prop)) {
794 delete doc[prop];
795 }
796 }
797 }
798 }
799 } catch (e) {
800 // do nothing
801 }
802 }
803 },
804
805 onLoad: function() {
806 let me = this,
807 doc = me.getDoc(),
808 fn = me.onRelayedEvent;
809
810 if (doc) {
811 try {
812 // These events need to be relayed from the inner document (where they stop
813 // bubbling) up to the outer document. This has to be done at the DOM level so
814 // the event reaches listeners on elements like the document body. The effected
815 // mechanisms that depend on this bubbling behavior are listed to the right
816 // of the event.
817 Ext.get(doc).on(
818 me._docListeners = {
819 mousedown: fn, // menu dismisal (MenuManager) and Window onMouseDown (toFront)
820 mousemove: fn, // window resize drag detection
821 mouseup: fn, // window resize termination
822 click: fn, // not sure, but just to be safe
823 dblclick: fn, // not sure again
824 scope: me,
825 },
826 );
827 } catch (e) {
828 // cannot do this xss
829 }
830
831 // We need to be sure we remove all our events from the iframe on unload or we're going to LEAK!
832 Ext.get(this.getWin()).on('beforeunload', me.cleanupListeners, me);
833
834 this.el.unmask();
835 this.fireEvent('load', this);
836 } else if (me.src) {
837 this.el.unmask();
838 this.fireEvent('error', this);
839 }
840 },
841
842 onRelayedEvent: function(event) {
843 // relay event from the iframe's document to the document that owns the iframe...
844
845 let iframeEl = this.iframeEl,
846
847 // Get the left-based iframe position
848 iframeXY = iframeEl.getTrueXY(),
849 originalEventXY = event.getXY(),
850
851 // Get the left-based XY position.
852 // This is because the consumer of the injected event will
853 // perform its own RTL normalization.
854 eventXY = event.getTrueXY();
855
856 // the event from the inner document has XY relative to that document's origin,
857 // so adjust it to use the origin of the iframe in the outer document:
858 event.xy = [iframeXY[0] + eventXY[0], iframeXY[1] + eventXY[1]];
859
860 event.injectEvent(iframeEl); // blame the iframe for the event...
861
862 event.xy = originalEventXY; // restore the original XY (just for safety)
863 },
864
865 load: function(src) {
866 let me = this,
867 text = me.loadMask,
868 frame = me.getFrame();
869
870 if (me.fireEvent('beforeload', me, src) !== false) {
871 if (text && me.el) {
872 me.el.mask(text);
873 }
874
875 frame.src = me.src = src || me.src;
876 }
877 },
878 });