-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Core.js
4133 lines (3628 loc) · 144 KB
/
Core.js
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
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*!
* ${copyright}
*/
// Provides the real core class sap.ui.core.Core of SAPUI5
sap.ui.define([
'jquery.sap.global',
'sap/ui/Device',
'sap/ui/Global',
'sap/ui/base/BindingParser',
'sap/ui/base/DataType',
'sap/ui/base/EventProvider',
'sap/ui/base/Interface',
'sap/ui/base/Object',
'sap/ui/base/ManagedObject',
'./Component',
'./Configuration',
'./Control',
'./Element',
'./ElementMetadata',
'./FocusHandler',
'./RenderManager',
'./ResizeHandler',
'./ThemeCheck',
'./UIArea',
'./message/MessageManager',
"sap/ui/util/ActivityDetection",
"sap/ui/dom/getScrollbarSize",
"sap/base/i18n/ResourceBundle",
"sap/base/Log",
"sap/ui/performance/Measurement",
"sap/ui/security/FrameOptions",
"sap/base/assert",
"sap/ui/dom/includeStylesheet",
"sap/base/util/ObjectPath",
"sap/base/util/Version",
"sap/base/util/array/uniqueSort",
"sap/base/util/uid",
'sap/ui/performance/trace/initTraces',
'sap/base/util/LoaderExtensions',
'sap/base/util/isEmptyObject',
'sap/base/util/each',
'sap/ui/events/jquery/EventSimulation'
],
function(
jQuery,
Device,
Global,
BindingParser,
DataType,
EventProvider,
Interface,
BaseObject,
ManagedObject,
Component,
Configuration,
Control,
Element,
ElementMetadata,
FocusHandler,
RenderManager,
ResizeHandler,
ThemeCheck,
UIArea,
MessageManager,
ActivityDetection,
getScrollbarSize,
ResourceBundle,
Log,
Measurement,
FrameOptions,
assert,
includeStylesheet,
ObjectPath,
Version,
uniqueSort,
uid,
initTraces,
LoaderExtensions,
isEmptyObject,
each
/* ,EventSimulation */
) {
"use strict";
/*global Promise, XMLHttpRequest */
/**
* Executes an 'eval' for its arguments in the global context (without closure variables).
*/
function globalEval() {
/*eslint-disable no-eval */
eval(arguments[0]);
/*eslint-enable no-eval */
}
// when the Core module has been executed before, don't execute it again
if (sap.ui.getCore && sap.ui.getCore()) {
return sap.ui.getCore();
}
// Initialize SAP Passport or FESR
initTraces();
// share the rendering log with the UIArea
var oRenderLog = UIArea._oRenderLog;
/**
* Set of libraries that have been loaded and initialized already.
* This is maintained separately from Core.mLibraries to protect it against
* modification from the outside (objects in mLibraries are currently exposed
* by getLoadedLibraries())
*/
var mLoadedLibraries = {};
/**
* Bookkeeping for the preloading of libraries.
*
* Might contain an object for each library (keyed by the library name).
* While the preload is pending for a library, the object has a property preload = true.
* In any case, the object contains a promise that fulfills / rejects when the preload
* fulfills / rejects.
* @private
*/
var mLibraryPreloadBundles = {};
/**
* EventProvider instance, EventProvider is no longer extended
* @private
*/
var _oEventProvider;
/*
* Internal class that can help to synchronize a set of asynchronous tasks.
* Each task must be registered in the sync point by calling startTask with
* an (purely informative) title. The returned value must be used in a later
* call to finishTask.
* When finishTask has been called for all tasks that have been started,
* the fnCallback will be fired.
* When a timeout is given and reached, the callback is called at that
* time, no matter whether all tasks have been finished or not.
*/
var SyncPoint = function (sName, fnCallback) {
var aTasks = [],
iOpenTasks = 0,
iFailures = 0;
this.startTask = function(sTitle) {
var iId = aTasks.length;
aTasks[iId] = { name : sTitle, finished : false };
iOpenTasks++;
return iId;
};
this.finishTask = function(iId, bSuccess) {
if ( !aTasks[iId] || aTasks[iId].finished ) {
throw new Error("trying to finish non existing or already finished task");
}
aTasks[iId].finished = true;
iOpenTasks--;
if ( bSuccess === false ) {
iFailures++;
}
if ( iOpenTasks === 0 ) {
Log.info("Sync point '" + sName + "' finished (tasks:" + aTasks.length + ", open:" + iOpenTasks + ", failures:" + iFailures + ")");
finish();
}
};
function finish() {
if ( fnCallback ) {
fnCallback(iOpenTasks, iFailures);
}
fnCallback = null;
}
Log.info("Sync point '" + sName + "' created");
};
/**
* @class Core Class of the SAP UI Library.
*
* This class boots the Core framework and makes it available for the application
* via method <code>sap.ui.getCore()</code>.
*
* Example:
* <pre>
*
* var oCore = sap.ui.getCore();
*
* </pre>
*
* With methods of the Core framework you can {@link #attachInit execute code} after the framework has been initialized.
* It provides access to the {@link #getConfiguration configuration} and exposes events that
* an application or a control can register to (e.g. {@link #event:localizationChanged localizationChanged},
* {@link #event:parseError parseError}, {@link #event:validationError validationError},
* {@link #event:formatError formatError}, {@link #event:validationSuccess validationSuccess}).
*
* Example:
* <pre>
*
* oCore.attachInit(function() {
* if ( oCore.getConfiguration().getRTL() ) {
* ...
* }
* });
*
* oCore.attachLocalizationChanged(function(oEvent) {
* ...
* });
*
* </pre>
*
* @extends sap.ui.base.Object
* @final
* @author SAP SE
* @version ${version}
* @alias sap.ui.core.Core
* @public
* @hideconstructor
*/
var Core = BaseObject.extend("sap.ui.core.Core", /** @lends sap.ui.core.Core.prototype */ {
constructor : function() {
var that = this,
METHOD = "sap.ui.core.Core";
// when a Core instance has been created before, don't create another one
if (sap.ui.getCore && sap.ui.getCore()) {
Log.error("Only the framework must create an instance of sap/ui/core/Core." +
" To get access to its functionality, use sap.ui.getCore().");
return sap.ui.getCore();
}
BaseObject.call(this);
_oEventProvider = new EventProvider();
// Generate all functions from EventProvider for backward compatibility
["attachEvent", "detachEvent", "getEventingParent"].forEach(function (sFuncName) {
Core.prototype[sFuncName] = _oEventProvider[sFuncName].bind(_oEventProvider);
});
/**
* Whether the core has been booted
* @private
*/
this.bBooted = false;
/**
* Whether the core has been initialized
* @private
*/
this.bInitialized = false;
/**
* Whether the DOM is ready (document.ready)
* @private
*/
this.bDomReady = false;
/**
* Available plugins in the order of registration.
* @private
*/
this.aPlugins = [];
/**
* Collection of loaded or adhoc created libraries, keyed by their name.
* @private
*/
this.mLibraries = {};
/**
* Already loaded resource bundles keyed by library and locale.
* @private
* @see sap.ui.core.Core.getLibraryResourceBundle
*/
this.mResourceBundles = {};
/**
* Currently created UIAreas keyed by their id.
* @private
* @todo FIXME how can a UI area ever be removed?
*/
this.mUIAreas = {};
/**
* Default model used for databinding
* @private
*/
this.oModels = {};
/**
* The event bus (initialized lazily)
* @private
*/
this.oEventBus = null;
/**
* Map of of created Elements keyed by their id.
*
* Each element registers itself in its constructor and deregisters itself in its
* destroy method.
*
* @private
* @todo get rid of this collection as it represents a candidate for memory leaks
*/
this.mElements = {};
/**
* Map of of created objects structured by their type which contains a map
* containing the created objects keyed by their type.
*
* Each object registers itself in its constructor and deregisters itself in its
* destroy method.
*
* @private
* @todo get rid of this collection as it represents a candidate for memory leaks
*/
this.mObjects = {
"component": {},
"template": {}
};
/**
* The instance of the root component (defined in the configuration {@link sap.ui.core.Configuration#getRootComponent})
* @private
*/
this.oRootComponent = null;
/**
* Ordered collection of initEvent listeners
* Moved here (before boot()) so that the libraries can be registered for lazy load!!
* @private
*/
this.aInitListeners = [];
/**
* Whether the legacy library has to be loaded.
* @private
*/
this.bInitLegacyLib = false;
/**
* The ID of a timer that will execute the next rendering.
*
* A non-falsy value indicates that a timer exists already, or at least that no
* new timer needs to be created as. During the boot phase, this member is set
* to the special value <code>this</code> which is non-falsy and which should never
* represent a valid timer ID (no chance of misinterpretation).
*/
this._sRerenderTimer = this;
/**
* Tasks that are called just before the rendering starts.
* @private
*/
this.aPrerenderingTasks = [];
Log.info("Creating Core",null,METHOD);
Measurement.start("coreComplete", "Core.js - complete");
Measurement.start("coreBoot", "Core.js - boot");
Measurement.start("coreInit", "Core.js - init");
/**
* Object holding the interpreted configuration
* Initialized from the global "sap-ui-config" object and from URL parameters
* @private
*/
this.oConfiguration = new Configuration(this);
// initialize frameOptions script (anti-clickjacking, etc.)
var oFrameOptionsConfig = this.oConfiguration["frameOptionsConfig"] || {};
oFrameOptionsConfig.mode = this.oConfiguration.getFrameOptions();
oFrameOptionsConfig.whitelistService = this.oConfiguration.getWhitelistService();
this.oFrameOptions = new FrameOptions(oFrameOptionsConfig);
// enable complex bindings if configured
if ( this.oConfiguration["bindingSyntax"] === "complex" ) {
ManagedObject.bindingParser = BindingParser.complexParser;
}
// switch bindingParser to designTime mode if configured
if (this.oConfiguration["xx-designMode"] == true ) {
BindingParser._keepBindingStrings = true;
}
// let Element and Component get friend access to the respective register/deregister methods
this._grantFriendAccess();
// handle modules
var aModules = this.oConfiguration.modules;
if ( this.oConfiguration.getDebug() ) {
// add debug module if configured
aModules.unshift("sap.ui.debug.DebugEnv");
}
// enforce the core library as the first loaded module
var i = aModules.indexOf("sap.ui.core.library");
if ( i != 0 ) {
if ( i > 0 ) {
aModules.splice(i,1);
}
aModules.unshift("sap.ui.core.library");
}
// enable LessSupport if specified in configuration
if (this.oConfiguration["xx-lesssupport"] && aModules.indexOf("sap.ui.core.plugin.LessSupport") == -1) {
Log.info("Including LessSupport into declared modules");
aModules.push("sap.ui.core.plugin.LessSupport");
}
// determine preload mode (e.g. resolve default or auto)
var sPreloadMode = this.oConfiguration.preload;
// if debug sources are requested, then the preload feature must be deactivated
if ( window["sap-ui-debug"] === true ) {
sPreloadMode = "";
}
// when the preload mode is 'auto', it will be set to 'async' or 'sync' for optimized sources
// depending on whether the ui5loader is configured async
if ( sPreloadMode === "auto" ) {
if (window["sap-ui-optimized"]) {
sPreloadMode = sap.ui.loader.config().async ? "async" : "sync";
} else {
sPreloadMode = "";
}
}
// write back the determined mode for later evaluation (e.g. loadLibrary)
this.oConfiguration.preload = sPreloadMode;
// This flag controls the core initialization flow.
// We can switch to async when an async preload is used or the ui5loader
// is in async mode. The latter might also happen for debug scenarios
// where no preload is used at all.
var bAsync = sPreloadMode === "async" || sap.ui.loader.config().async;
// evaluate configuration for library preload file types
this.oConfiguration['xx-libraryPreloadFiles'].forEach(function(v){
var fields = String(v).trim().split(/\s*:\s*/),
name = fields[0],
fileType = fields[1];
if ( fields.length === 1 ) {
fileType = name;
name = '';
}
if ( /^(?:none|js|json|both)$/.test(fileType) ) {
mLibraryPreloadFileTypes[name] = fileType;
}
});
Log.info("Declared modules: " + aModules, METHOD);
this._setupThemes();
this._setupContentDirection();
this._setupBrowser();
this._setupOS();
this._setupLang();
this._setupAnimation();
// create accessor to the Core API early so that initLibrary and others can use it
/**
* Retrieve the {@link sap.ui.core.Core SAPUI5 Core} instance for the current window.
* @returns {sap.ui.core.Core} the API of the current SAPUI5 Core instance.
* @public
* @function
*/
sap.ui.getCore = function() {
return that.getInterface();
};
// create the RenderManager so it can be used already
this.oRenderManager = new RenderManager();
// sync point 1 synchronizes document ready and rest of UI5 boot
var oSyncPoint1 = new SyncPoint("UI5 Document Ready", function(iOpenTasks, iFailures) {
that.bDomReady = true;
that.init();
});
var iDocumentReadyTask = oSyncPoint1.startTask("document.ready");
var iCoreBootTask = oSyncPoint1.startTask("preload and boot");
var fnContentLoadedCallback = function() {
Log.trace("document is ready");
oSyncPoint1.finishTask(iDocumentReadyTask);
document.removeEventListener("DOMContentLoaded", fnContentLoadedCallback);
};
// immediately execute callback if the ready state is already 'complete'
if (document.readyState !== "loading") {
fnContentLoadedCallback();
} else {
// task 1 is to wait for document.ready
document.addEventListener("DOMContentLoaded", fnContentLoadedCallback);
}
// sync point 2 synchronizes all library preloads and the end of the bootstrap script
var oSyncPoint2 = new SyncPoint("UI5 Core Preloads and Bootstrap Script", function(iOpenTasks, iFailures) {
Log.trace("Core loaded: open=" + iOpenTasks + ", failures=" + iFailures);
that._boot(bAsync, function() {
oSyncPoint1.finishTask(iCoreBootTask);
Measurement.end("coreBoot");
});
});
// a helper task to prevent the premature completion of oSyncPoint2
var iCreateTasksTask = oSyncPoint2.startTask("create sp2 tasks task");
// load the version info file in case of a custom theme to determine
// the distribution version which should be provided in library.css requests.
if (this.oConfiguration["versionedLibCss"]) {
var iVersionInfoTask = oSyncPoint2.startTask("load version info");
var fnCallback = function(oVersionInfo) {
if (oVersionInfo) {
Log.trace("Loaded \"sap-ui-version.json\".");
} else {
Log.error("Could not load \"sap-ui-version.json\".");
}
oSyncPoint2.finishTask(iVersionInfoTask);
};
// only use async mode if library preload is async
var vReturn = sap.ui.getVersionInfo({ async: bAsync, failOnError: false });
if (vReturn instanceof Promise) {
vReturn.then(fnCallback, function(oError) {
// this should only happen when there is a script error as "failOnError=false"
// prevents throwing a loading error (e.g. HTTP 404)
Log.error("Unexpected error when loading \"sap-ui-version.json\": " + oError);
oSyncPoint2.finishTask(iVersionInfoTask);
});
} else {
fnCallback(vReturn);
}
}
// when a boot task is configured, add it to syncpoint2
var fnCustomBootTask = this.oConfiguration["xx-bootTask"];
if ( fnCustomBootTask ) {
var iCustomBootTask = oSyncPoint2.startTask("custom boot task");
fnCustomBootTask( function(bSuccess) {
oSyncPoint2.finishTask(iCustomBootTask, typeof bSuccess === "undefined" || bSuccess === true );
});
}
this._polyfillFlexbox();
// when the bootstrap script has finished, it calls sap.ui.getCore().boot()
var iBootstrapScriptTask = oSyncPoint2.startTask("bootstrap script");
this.boot = function() {
if (this.bBooted) {
return;
}
this.bBooted = true;
oSyncPoint2.finishTask(iBootstrapScriptTask);
};
if ( sPreloadMode === "sync" || sPreloadMode === "async" ) {
// determine set of libraries
var aLibs = aModules.reduce(function(aResult, sModule) {
var iPos = sModule.search(/\.library$/);
if ( iPos >= 0 ) {
aResult.push(sModule.slice(0, iPos));
}
return aResult;
}, []);
var preloaded = this.loadLibraries(aLibs, {
async: bAsync,
preloadOnly: true
});
if ( bAsync ) {
var iPreloadLibrariesTask = oSyncPoint2.startTask("preload bootstrap libraries");
preloaded.then(function() {
oSyncPoint2.finishTask(iPreloadLibrariesTask);
}, function() {
oSyncPoint2.finishTask(iPreloadLibrariesTask, false);
});
}
}
// initializes the application cachebuster mechanism if configured
var aACBConfig = this.oConfiguration.getAppCacheBuster();
if (aACBConfig && aACBConfig.length > 0) {
var AppCacheBuster = sap.ui.requireSync('sap/ui/core/AppCacheBuster');
AppCacheBuster.boot(oSyncPoint2);
}
// Initialize support info stack
if (this.oConfiguration.getSupportMode() !== null) {
var iSupportInfoTask = oSyncPoint2.startTask("support info script");
var fnCallbackSupportBootstrapInfo = function(Support, Bootstrap) {
Support.initializeSupportMode(that.oConfiguration.getSupportMode(), bAsync);
Bootstrap.initSupportRules(that.oConfiguration.getSupportMode());
oSyncPoint2.finishTask(iSupportInfoTask);
};
if (bAsync) {
sap.ui.require(["sap/ui/core/support/Support", "sap/ui/support/Bootstrap"], fnCallbackSupportBootstrapInfo);
} else {
Log.warning("Synchronous loading of Support mode. Set preload configuration to 'async' or switch to asynchronous bootstrap to prevent these synchronous request.", "SyncXHR", null, function() {
return {
type: "SyncXHR",
name: "support-mode"
};
});
fnCallbackSupportBootstrapInfo(
sap.ui.requireSync("sap/ui/core/support/Support"),
sap.ui.requireSync("sap/ui/support/Bootstrap")
);
}
}
oSyncPoint2.finishTask(iCreateTasksTask);
},
metadata : {
publicMethods: ["boot", "isInitialized","isThemeApplied","attachInitEvent","attachInit","getRenderManager","createRenderManager",
"getConfiguration", "setRoot", "createUIArea", "getUIArea", "getUIDirty", "getElementById",
"getCurrentFocusedControlId", "getControl", "getComponent", "getTemplate", "lock", "unlock","isLocked",
"attachEvent","detachEvent","applyChanges", "getEventBus",
"applyTheme","setThemeRoot","attachThemeChanged","detachThemeChanged","getStaticAreaRef",
"attachThemeScopingChanged","detachThemeScopingChanged","fireThemeScopingChanged",
"notifyContentDensityChanged",
"registerPlugin","unregisterPlugin","getLibraryResourceBundle", "byId",
"getLoadedLibraries", "loadLibrary", "loadLibraries", "initLibrary",
"includeLibraryTheme", "setModel", "getModel", "hasModel", "isMobile",
"attachControlEvent", "detachControlEvent", "attachIntervalTimer", "detachIntervalTimer",
"attachParseError", "detachParseError", "fireParseError",
"attachValidationError", "detachValidationError", "fireValidationError",
"attachFormatError", "detachFormatError", "fireFormatError",
"attachValidationSuccess", "detachValidationSuccess", "fireValidationSuccess",
"attachLocalizationChanged", "detachLocalizationChanged",
"attachLibraryChanged", "detachLibraryChanged",
"isStaticAreaRef", "createComponent", "getRootComponent", "getApplication",
"setMessageManager", "getMessageManager","byFieldGroupId",
"addPrerenderingTask"]
}
});
/**
* Map of event names and ids, that are provided by this class
* @private
*/
Core.M_EVENTS = {ControlEvent: "ControlEvent", UIUpdated: "UIUpdated", ThemeChanged: "ThemeChanged", ThemeScopingChanged: "themeScopingChanged", LocalizationChanged: "localizationChanged",
LibraryChanged : "libraryChanged",
ValidationError : "validationError", ParseError : "parseError", FormatError : "formatError", ValidationSuccess : "validationSuccess"};
// Id of the static UIArea
var STATIC_UIAREA_ID = "sap-ui-static";
/**
* The core allows some friend components to register/deregister themselves
* @private
*/
Core.prototype._grantFriendAccess = function() {
var that = this;
// grant ElementMetadata "friend" access to Core for registration
ElementMetadata.prototype.register = function(oMetadata) {
that.registerElementClass(oMetadata);
};
// grant Element "friend" access to Core for (de-)registration
Element.prototype.register = function() {
that.registerElement(this);
};
Element.prototype.deregister = function() {
that.deregisterElement(this);
};
// grant Element "friend" access to Core / FocusHandler to update the given elements focus info
Element._updateFocusInfo = function(oElement) {
if (that.oFocusHandler) {
that.oFocusHandler.updateControlFocusInfo(oElement);
}
};
// grant Component "friend" access to Core for (de-)registration
Component.prototype.register = function() {
that.registerObject(this);
};
Component.prototype.deregister = function() {
var sComponentId = this.sId;
for (var sElementId in that.mElements) {
var oElement = that.mElements[sElementId];
if ( oElement._sapui_candidateForDestroy && oElement._sOwnerId === sComponentId && !oElement.getParent() ) {
Log.debug("destroying dangling template " + oElement + " when destroying the owner component");
oElement.destroy();
}
}
that.deregisterObject(this);
};
};
/**
* Initializes the window "sap-ui-config" property, sets theme roots, initializes sTheme, sets theme CSS classes
* @private
*/
Core.prototype._setupThemes = function() {
var METHOD = "sap.ui.core.Core";
var oCfgData = window["sap-ui-config"];
// Configuration might have a themeRoot, if so integrate it in themeroots
if ( this.oConfiguration.themeRoot ) {
oCfgData = oCfgData || {};
oCfgData.themeroots = oCfgData.themeroots || {};
oCfgData.themeroots[this.oConfiguration.getTheme()] = this.oConfiguration.themeRoot;
}
if (oCfgData) {
// read themeRoots configuration
if (oCfgData.themeroots) {
for (var themeName in oCfgData.themeroots) {
var themeRoot = oCfgData.themeroots[themeName];
if (typeof themeRoot === "string") {
this.setThemeRoot(themeName, themeRoot);
} else {
for (var lib in themeRoot) {
if (lib.length > 0) {
this.setThemeRoot(themeName, [lib], themeRoot[lib]);
} else {
this.setThemeRoot(themeName, themeRoot[lib]);
}
}
}
}
}
}
// set CSS class for the theme name
this.sTheme = this.oConfiguration.getTheme();
document.documentElement.classList.add("sapUiTheme-" + this.sTheme);
Log.info("Declared theme " + this.sTheme,null,METHOD);
};
/**
* Set the document's dir property
* @private
*/
Core.prototype._setupContentDirection = function() {
var METHOD = "sap.ui.core.Core",
sDir = this.oConfiguration.getRTL() ? "rtl" : "ltr";
document.documentElement.setAttribute("dir", sDir); // webkit does not allow setting document.dir before the body exists
Log.info("Content direction set to '" + sDir + "'",null,METHOD);
};
/**
* Set the body's browser-related attributes.
* @private
*/
Core.prototype._setupBrowser = function() {
var METHOD = "sap.ui.core.Core";
//set the browser for CSS attribute selectors. do not move this to the onload function because sf and ie do not
//use the classes
var html = document.documentElement;
var b = Device.browser;
var id = b.name;
if (id) {
if (id === b.BROWSER.SAFARI && b.mobile) {
id = "m" + id;
}
id = id + (b.version === -1 ? "" : Math.floor(b.version));
html.dataset.sapUiBrowser = id;
Log.debug("Browser-Id: " + id, null, METHOD);
}
};
/**
* Set the body's OS-related attribute and CSS class
* @private
*/
Core.prototype._setupOS = function(html) {
var html = document.documentElement;
html.dataset.sapUiOs = Device.os.name + Device.os.versionStr;
var osCSS = null;
switch (Device.os.name) {
case Device.os.OS.IOS:
osCSS = "sap-ios";
break;
case Device.os.OS.ANDROID:
osCSS = "sap-android";
break;
case Device.os.OS.BLACKBERRY:
osCSS = "sap-bb";
break;
case Device.os.OS.WINDOWS_PHONE:
osCSS = "sap-winphone";
break;
}
if (osCSS) {
html.classList.add(osCSS);
}
};
/**
* Set the body's lang attribute and attach the localization change event
* @private
*/
Core.prototype._setupLang = function() {
var html = document.documentElement;
// append the lang info to the document (required for ARIA support)
var fnUpdateLangAttr = function() {
var oLocale = this.oConfiguration.getLocale();
oLocale ? html.setAttribute("lang", oLocale.toString()) : html.removeAttribute("lang");
};
fnUpdateLangAttr.call(this);
// listen to localization change event to update the lang info
this.attachLocalizationChanged(fnUpdateLangAttr, this);
};
/**
* Set the body's Animation-related attribute and configures jQuery animations accordingly.
* @private
*/
Core.prototype._setupAnimation = function() {
// We check for the existence of the configuration object, because the _setupAnimation function
// will first be called from the Configuration constructor within the Core constructor.
// During this first call, the configuration object is not yet set on the Core instance.
if (this.oConfiguration) {
var html = document.documentElement;
var bAnimation = this.oConfiguration.getAnimation();
html.dataset.sapUiAnimation = bAnimation ? "on" : "off";
if (typeof jQuery !== "undefined") {
jQuery.fx.off = !bAnimation;
}
var sAnimationMode = this.oConfiguration.getAnimationMode();
html.dataset.sapUiAnimationMode = sAnimationMode;
}
};
/**
* Initializes the jQuery.support.useFlexBoxPolyfill property
* @private
*/
Core.prototype._polyfillFlexbox = function() {
/**
* Whether the current browser needs a polyfill as a fallback for flex box support
* @type {boolean}
* @private
* @name jQuery.support.useFlexBoxPolyfill
* @since 1.12.0
* @deprecated since version 1.16.0
*
* For backwards compatibility we can't remove the deprecated flexbox polyfill.
* However, if the compatibility version is 1.16 or higher then the polyfill
* should not be used.
*/
jQuery.support.useFlexBoxPolyfill = false;
};
/**
* Boots the core and injects the necessary CSS and JavaScript files for the library.
* Applications shouldn't call this method. It is automatically called by the bootstrap scripts (e.g. sap-ui-core.js)
*
* @param {boolean} bAsync - Flag if modules should be loaded asynchronously
* @param {function} fnCallback - Callback after modules have been loaded
* @returns {undefined|Promise}
* @private
*/
Core.prototype._boot = function(bAsync, fnCallback) {
// if a list of preloaded library CSS is configured, request a merged CSS (if application did not already do it)
var aCSSLibs = this.oConfiguration['preloadLibCss'];
if (aCSSLibs && aCSSLibs.length > 0 && !aCSSLibs.appManaged) {
this.includeLibraryTheme("sap-ui-merged", undefined, "?l=" + aCSSLibs.join(","));
}
// load all modules now
if ( bAsync ) {
return this._requireModulesAsync().then(function() {
fnCallback();
});
}
Log.warning("Modules and libraries declared via bootstrap-configuration are loaded synchronously. Set preload configuration to" +
" 'async' or switch to asynchronous bootstrap to prevent these requests.", "SyncXHR", null, function() {
return {
type: "SyncXHR",
name: "legacy-module"
};
});
this.oConfiguration.modules.forEach( function(mod) {
var m = mod.match(/^(.*)\.library$/);
if ( m ) {
this.loadLibrary(m[1]);
} else {
// data-sap-ui-modules might contain legacy jquery.sap.* modules
sap.ui.requireSync( /^jquery\.sap\./.test(mod) ? mod : mod.replace(/\./g, "/"));
}
}.bind(this));
fnCallback();
};
Core.prototype._requireModulesAsync = function() {
var aLibs = [],
aModules = [];
this.oConfiguration.modules.forEach(function(sModule) {
var m = sModule.match(/^(.*)\.library$/);
if (m) {
aLibs.push(m[1]);
} else {
// data-sap-ui-modules might contain legacy jquery.sap.* modules
aModules.push(/^jquery\.sap\./.test(sModule) ? sModule : sModule.replace(/\./g, "/"));
}
});
// TODO: require libs and modules in parallel or define a sequence?
return Promise.all([
this.loadLibraries(aLibs),
new Promise(function(resolve) {
sap.ui.require(aModules, function() {
resolve(Array.prototype.slice.call(arguments));
});
})
]);
};
/**
* Applies the theme with the given name (by loading the respective style sheets, which does not disrupt the application).
*
* By default, the theme files are expected to be located at path relative to the respective control library ([libraryLocation]/themes/[themeName]).
* Different locations can be configured by using the method setThemePath() or by using the second parameter "sThemeBaseUrl" of applyTheme().
* Usage of this second parameter is a shorthand for setThemePath and internally calls setThemePath, so the theme location is then known.
*
* sThemeBaseUrl is a single URL to specify the default location of all theme files. This URL is the base folder below which the control library folders
* are located. E.g. if the CSS files are not located relative to the root location of UI5, but instead they are at locations like
* http://my.server/myapp/resources/sap/ui/core/themes/my_theme/library.css
* then the URL that needs to be given is:
* http://my.server/myapp/resources
* All theme resources are then loaded from below this folder - except if for a certain library a different location has been registered.
*
* If the theme resources are not all either below this base location or with their respective libraries, then setThemePath must be
* used to configure individual locations.
*
* @param {string} sThemeName the name of the theme to be loaded
* @param {string} [sThemeBaseUrl] the (optional) base location of the theme
* @public
*/
Core.prototype.applyTheme = function(sThemeName, sThemeBaseUrl) {
assert(typeof sThemeName === "string", "sThemeName must be a string");
assert(typeof sThemeBaseUrl === "string" || typeof sThemeBaseUrl === "undefined", "sThemeBaseUrl must be a string or undefined");
sThemeName = this.oConfiguration._normalizeTheme(sThemeName, sThemeBaseUrl);
if (sThemeBaseUrl) {
this.setThemeRoot(sThemeName, sThemeBaseUrl);
}
// only apply the theme if it is different from the active one
if (sThemeName && this.sTheme != sThemeName) {
var sCurrentTheme = this.sTheme;
var html = document.documentElement;
this._updateThemeUrls(sThemeName, /* bSuppressFOUC */ true);
this.sTheme = sThemeName;
this.oConfiguration._setTheme(sThemeName);
// modify the <html> tag's CSS class with the theme name
html.classList.remove("sapUiTheme-" + sCurrentTheme);
html.classList.add("sapUiTheme-" + sThemeName);
// notify the listeners
if ( this.oThemeCheck ) {
this.oThemeCheck.fireThemeChangedEvent(false);
}
}
};
// this function is also used by "sap.ui.core.ThemeCheck" to load a fallback theme for a single library
Core.prototype._updateThemeUrl = function(oLink, sThemeName, bSuppressFOUC) {
var sLibName = oLink.id.slice(13), // length of "sap-ui-theme-"
iQueryIndex = oLink.href.search(/[?#]/),
sLibFileName,
sQuery,
sStandardLibFilePrefix = "library",
sRTL = this.oConfiguration.getRTL() ? "-RTL" : "",
sHref,
pos;